Raniere Silva
Raniere Silva

Reputation: 2697

Why Python's str.format is slower than string concat

Not the perfect benchmark but

$python --version
Python 3.4.2
$ python -m timeit 'print("foo" + str(3.14) + "bar")'
100000 loops, best of 3: 16.4 usec per loop
$ python -m timeit 'print("foo{}bar".format(3.14))'
100000 loops, best of 3: 19.2 usec per loop

Upvotes: 0

Views: 117

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47172

Because of the extra work that .format() is doing.

The .format() is actually not the work of the String class itself it's from the Formatter class which is why you're seeing the extra few seconds, it's offloading the work to a specialised class that's doing all of the heavy lifting.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249123

You're right, the one using format is slightly slower. But who cares? You wouldn't do this sort of thing in a performance-critical app, right?

If you want a possible explanation of why format should be slower, it's because it must parse the format string. This is rather more involved than simply converting a number to a string and concatenating. I'm surprised the difference is as small as it is.

Upvotes: 5

Related Questions