Referring to this Python List Comprehension Vs. Map question, can someone explain why List Comprehensions gives better results over map when list comprehension does not call a function, even when there is no lambda function in the map but gives the worst result when calling a function?
import timeit
print timeit.Timer('''[i**2 for i in xrange(100)]''').timeit(number = 100000)
print timeit.Timer('''map(lambda i: i**2, xrange(100))''').timeit(number = 100000)
print timeit.Timer(setup="""def my_pow(i):
return i**2
""",stmt="""map(my_pow, xrange(100))""").timeit(number = 100000)
print timeit.Timer(setup="""def my_pow(i):
return i**2
""",stmt='''[my_pow(i) for i in xrange(100)]''').timeit(number = 100000)
results:
1.03697046805 <-- list comprehension without function call
1.96599485313 <-- map with lambda function
1.92951520483 <-- map with function call
2.23419570042 <-- list comprehension with function call
mapis a lambda or a regular function, the overhead is still there. No idea why a list comprehension with a function call would be slower thanmap()though. - millimoosemy_powdefinition being interpreted only once for the whole timeit execution (in setup) and lambda being defined for each iteration. It's a valid question, and lambda probably contributes to it's version being slightly slower. - soulcheck