简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM