speedup up dictionary access

Martin von Loewis loewis at informatik.hu-berlin.de
Wed May 16 19:14:59 CEST 2001


Roy Smith <roy at panix.com> writes:

> One of the big time consumers in an application I'm writing is a cache 
> lookup in the inner loop of the program.  Right now, it looks something 
> like this:
> 
>    if (self.cache.has_key (name) and self.cache[name]) or self.check (name):
>       do stuff
> 
> check() returns 0 or 1 based on the value of name, and also inserts this 
> value into the cache.
> 
> I know that my cache hit ratio is going to be very high (almost 100%).  
> Would I do better writing it as:

I'd write

     if self.cache.get(name) or self.check(name):
       do stuff

.get returns None if name is not in the dict, or the value otherwise.

Regards,
Martin



More information about the Python-list mailing list