Hacker News new | past | comments | ask | show | jobs | submit login

I wonder if [x for x in xrange(NUMBER)] would be any faster. Yes it allocates an array but list comprehension is executed differently by python. I recall a talk by some Dropbox guy stating that it was one of their optimization strategies.

Didn't find the original talk but found this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loo...




Nitpick: that creates a list, not an array. It could be faster, but it's not the same benchmark. When you get to the point where the speed of loops matters it's better to reach for Cython, Numba, PyPy, etc.


Why wonder when you can test?

    % python -mtimeit '[x for x in xrange(1000)]'
    10000 loops, best of 3: 70.2 usec per loop
    % python -mtimeit 'for x in xrange(1000): pass'
    10000 loops, best of 3: 29 usec per loop

    % python -mtimeit '[x for x in xrange(100000)]'
    100 loops, best of 3: 7.03 msec per loop
    % python -mtimeit 'for x in xrange(100000): pass'
    100 loops, best of 3: 2.5 msec per loop




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: