Confused compare function :)

Ramchandra Apte maniandram01 at gmail.com
Sat Dec 8 22:07:50 EST 2012


On Thursday, 6 December 2012 17:44:17 UTC+5:30, Chris Angelico  wrote:
> On Thu, Dec 6, 2012 at 10:47 PM, Steven D'Aprano
> 
> <steve+comp.lang.python at pearwood.info> wrote:
> 
> > Not so. Which one is faster will depend on how often you expect to fail.
> 
> > If the keys are nearly always present, then:
> 
> >
> 
> > try:
> 
> >     do_stuff(mydict[k])
> 
> > except KeyError:
> 
> >     pass
> 
> >
> 
> > will be faster. Setting up a try block is very fast, about as fast as
> 
> > "pass", and faster than "if k in mydict".
> 
> >
> 
> > But if the key is often missing, then catching the exception will be
> 
> > slow, and the "if k in mydict" version may be faster. It depends on how
> 
> > often the key is missing.
> 
> >
> 
> 
> 
> Setting up the try/except is a constant time cost, while the
> 
> duplicated search for k inside the dictionary might depend on various
> 
> other factors. In the specific case of a Python dictionary, the
> 
> membership check is fairly cheap (assuming you're not the subject of a
> 
> hash collision attack - Py3.3 makes that a safe assumption), but if
> 
> you were about to execute a program and wanted to first find out if it
> 
> existed, that extra check could be ridiculously expensive, eg if the
> 
> path takes you on a network drive - or, worse, on multiple network
> 
> drives, which I have had occasion to do!
> 
> 
> 
> ChrisA

Not really. I remember a bug saying that only 256 hashes were required of known texts and then the randomization becomes useless.



More information about the Python-list mailing list