10 ms·
~$python -mtimeit "'a' + 'b' + 'c' + 'd'" 10000000 loops, best of 3: 0.026 usec per loop ~$python -mtimeit "''.join(('a','b','c','d'))" 10000000 loops, best
by kqueue 15y ago
~$python -mtimeit "'a' + 'b' + 'c' + 'd'"
10000000 loops, best of 3: 0.026 usec per loop
~$python -mtimeit "''.join(('a','b','c','d'))"
10000000 loops, best of 3: 0.197 usec per loop
- Ysx 15y agoInteresting! ''.join() has the advantage on longer strings though: $ python -mtimeit "'aaaaaaaaaaaaaaa' + 'bbbbbbbbbbbbbbb' + 'ccccccccccccccc' + 'ddddddddddddddd'" 1000000 loops, best of 3: 0.224 usec per loop $ python -mtimeit "''.join(('aaaaaaaaaaaaaaa','bbbbbbbbbbbbbbb','ccccccccccccccc','ddddddddddddddd'))" 10000000 loops, best of 3: 0.201 usec per loop
- kqueue 15y agoThat's definitely interesting.
- imurray 15y agoAlways worth checking. Although the relative merits change when doing many joins to build up a single long string. This recommendation is to go with .join() by default: In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations. — http://www.python.org/dev/peps/pep-0008/ http://www.python.org/dev/peps/pep-0008/ despite the fact it might not be better in CPython.
- deleted 15y ago[deleted]
- steve-howard 15y agoIt's not terribly surprising. Things that scale faster tend to have higher setup costs (cf sorting algorithms; insertion sort is the fastest for relatively small n).
- thristian 15y agoI believe the Python runtime has special-case handling for concatenating string-literals, and for concatenating string whose reference count is exactly 1. String concatenation isn't wholly defanged, though.
- podperson 15y agoYou're also constructing the array in the second test. For a fair test, add elements of an array vs. joining them.