Tip 63 Build, Then Print

Pythonic Programming — by Dmitry Zinoviev (75 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Avoid Function Calls; They Are Costly | TOC | Format with Formatted Strings 👉

★2.7, 3.4+ Function calls are costly in terms of execution time (Tip 62, Avoid Function Calls; They Are Costly), but few function calls are as expensive as calls to print and other input/output functions. Displaying visual output involves interacting with the operating system (slow on its own) and scrolling the console window (also slow). Compare the following two code fragments that accomplish precisely the same goal: display 1,000 letter a’s on one line.

​ ​# Print piece-wise​
​ ​for​ _ ​in​ range(1000):
​ ​print​(​'a'​, end=​''​)
​ ​print​()

​ ​# Build, then print​
​ a = 1000 * ​'a'​
​ ​print​(a)

The first fragment attacks the problem literally. It displays the letter 1,000 times without going to the next line and then finally breaks the line. The second fragment first builds a string that contains 1,000 a’s and then displays them at once.

The second fragment takes about 70 microseconds to execute on my computer, but the first one takes 480 microseconds — seven times slower.

Python string functions and operators are very efficient. If performance is important to you, you should construct as much output as possible as one string and use as few calls to print as possible to display it. Tip 64, Format with Formatted Strings, suggests how to speed up string…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.