Speed of Python 1.5.x vs 2.0

Alex Martelli aleaxit at yahoo.com
Fri Dec 22 06:53:25 EST 2000


"Steve Horne" <sh at ttsoftware.co.uk> wrote in message
news:dud64ts8mb7mlc41kht410q5g87ekb2nc5 at 4ax.com...
    [snip]
> I'd expect list comprehensions to work significantly faster than
> equivalent expressions using filter, map and lambdas - the reason
> being that the overhead of repeatedly calling the lambda should be
> avoided, not to mention avoiding the temp storage between the filter
> and map.
>
> I haven't tried this, but it might be worth a go.

You'll be disappointed, I fear... a typical simple case
produces not-very-significant differences, e.g.:

import time

def withMap(inList):
    return map(lambda x: x+1, inList)

def withLC(inList):
    return [x+1 for x in inList]

def stopWatch(function, N=100*1000):
    start = time.clock()
    function(range(N))
    stend = time.clock()
    return stend-start

print "Using map and lambda:     %f" % stopWatch(withMap)
print "Using list-comprehension: %f" % stopWatch(withMap)



D:\PySym>python tim.py
Using map and lambda:     0.499228
Using list-comprehension: 0.489680

D:\PySym>python tim.py
Using map and lambda:     0.502484
Using list-comprehension: 0.502492

D:\PySym>python tim.py
Using map and lambda:     0.491193
Using list-comprehension: 0.483273


There may be a tiny margin for the list comprehension, but
hardly anything worth writing home about.  And I remember
posts from a few months ago that identified cases in which
map was systematically faster (though, if I recall right,
not by all that much either).

Nor does adding a filtering step change much...:

import time

def withMap(inList):
    return map(lambda x: x+1, filter(lambda x: x%2, inList))

def withLC(inList):
    return [x+1 for x in inList if x%2]

def stopWatch(function, N=100*1000):
    start = time.clock()
    function(range(N))
    stend = time.clock()
    return stend-start

print "Using map and lambda:     %f" % stopWatch(withMap)
print "Using list-comprehension: %f" % stopWatch(withMap)


D:\PySym>python tim.py
Using map and lambda:     0.834212
Using list-comprehension: 0.808803

D:\PySym>python tim.py
Using map and lambda:     0.832734
Using list-comprehension: 0.818849

D:\PySym>python tim.py
Using map and lambda:     0.832896
Using list-comprehension: 0.819406


It may be 2% rather than 1%, but I strongly doubt such
differences can be considered meaningful for any real
Python use case.


Alex






More information about the Python-list mailing list