Should I use "if" or "try" (as a matter of speed)?
John Machin
sjmachin at lexicon.net
Sat Jul 9 21:01:56 EDT 2005
Roy Smith wrote:
> Well, you've now got a failure. I used to write Fortran on punch cards,
which were then fed into an OCR gadget? That's an efficient approach --
where I was, we had to write the FORTRAN [*] on coding sheets; KPOs
would then produce the punched cards.
[snip]
>
> 3) In some cases, they can lead to faster code. A classic example is
> counting occurances of items using a dictionary:
>
> count = {}
> for key in whatever:
> try:
> count[key] += 1
> except KeyError:
> count[key] = 1
>
> compared to
>
> count = {}
> for key in whatever:
> if count.hasKey(key):
Perhaps you mean has_key [*].
Perhaps you might like to try
if key in count:
It's believed to be faster (no attribute lookup, no function call).
[snip]
[*]
humanandcomputerlanguagesshouldnotimhousecaseandwordseparatorsascrutchesbuttheydosogetusedtoit
:-)
More information about the Python-list
mailing list