pointless musings on performance

MRAB python at mrabarnett.plus.com
Tue Nov 24 13:26:12 CET 2009


mk wrote:
> #!/usr/local/bin/python
> 
> import timeit
> 
> 
> def pythonic():
>     nonevar = None
>     zerovar = 0
>     for x in range(1000000):
>         if nonevar:
>             pass
>         if zerovar:
>             pass
> 
> def unpythonic():
>     nonevar = None
>     zerovar = 0
>     for x in range(1000000):
>         if nonevar is not None:
>             pass
>         if zerovar > 0:
>             pass
> 
> for f in [pythonic, unpythonic]:
>     print f.func_name, timeit.timeit(f, number=10)
> 
> 
> 
> # ./t.py
> pythonic 2.13092803955
> unpythonic 2.82064604759
> 
> Decidedly counterintuitive: are there special optimizations for "if 
> nonevar:" type of statements in cpython implementation?
> 
In what way is it counterintuitive? In 'pythonic' the conditions are
simpler, less work is being done, therefore it's faster.



More information about the Python-list mailing list