Hacker News new | ask | show | jobs
by psd1 1034 days ago
I agree with the improvement in readability but still like the bool/int equivalence:

    sum(int(age > 17) for age in ages)
Every nanosecond is vital!
1 comments

Interesting, so I did a little test:

  python -m timeit 'sum(1 for age in range(100000) if age > 17)'
  50 loops, best of 5: 5.08 msec per loop

  python -m timeit 'sum(int(age > 17) for age in range(100000))'
  50 loops, best of 5: 7.96 msec per loop

  python -m timeit 'sum(age > 17 for age in range(100000))'
  50 loops, best of 5: 4.78 msec per loop
Yep, in python function calls are not cheap, you’re usually better off avoiding them in tight loops.

Plus here on each iteration `int` has to be loaded from the globals before it can be called.