12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

When I ran this in IDLE on Windows XP with <strong>Python</strong> 2.5, here is what I found—listcomprehensions were roughly twice as fast as equivalent for loop statements, andmap was slightly quicker than list comprehensions when mapping a built-in functionsuch as abs (absolute value):2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]forStatement => 6.10899996758listComprehension => 3.51499986649mapFunction => 2.73399996758generatorExpression => 4.11600017548But watch what happens if we change this script to perform a real operation on eachiteration, such as addition:......def forStatement( ):res = []for x in range(size):res.append(x + 10)def listComprehension( ):res = [x + 10 for x in range(size)]def mapFunction( ):res = map((lambda x: x + 10), range(size))def generatorExpression( ):res = list(x + 10 for x in range(size))......The function-call requirement of the map call then makes it just as slow as the for loopstatements, despite the fact the looping statements version is larger in terms of code:2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]forStatement => 5.25699996948listComprehension => 2.68400001526mapFunction => 5.96900010109generatorExpression => 3.37400007248Because the interpreter optimizes so much internally, performance analysis of <strong>Python</strong>code like this is a very tricky affair. It’s virtually impossible to guess which methodwill perform the best—the best you can do is time your own code, on your computer,with your version of <strong>Python</strong>. In this case, all we can say for certain is that onthis <strong>Python</strong>, using a user-defined function in map calls can slow it down by at least afactor of 2, and that list comprehensions run quickest for this test.As I’ve mentioned before, however, performance should not be your primaryconcern when writing <strong>Python</strong> code—write for readability and simplicity first, thenoptimize later, if and only if needed. It could very well be that any of the four alternativesis quick enough for the data sets the program needs to process; if so, programclarity should be the chief goal.368 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!