Saturday, July 3, 2021

Python Which is faster string concatenation approach

 Python 3.6 changed the game for string concatenation of known components with Literal String Interpolation.


Given the test case from mkoistinen's answer, having strings


domain = 'some_really_long_example.com'

lang = 'en'

path = 'some/really/long/path/'

The contenders are


f'http://{domain}/{lang}/{path}' - 0.151 µs


'http://%s/%s/%s' % (domain, lang, path) - 0.321 µs


'http://' + domain + '/' + lang + '/' + path - 0.356 µs


''.join(('http://', domain, '/', lang, '/', path)) - 0.249 µs (notice that building a constant-length tuple is slightly faster than building a constant-length list).


Thus currently the shortest and the most beautiful code possible is also fastest.


In alpha versions of Python 3.6 the implementation of f'' strings was the slowest possible - actually the generated byte code is pretty much equivalent to the ''.join() case with unnecessary calls to str.__format__ which without arguments would just return self unchanged. These inefficiencies were addressed before 3.6 final.


The speed can be contrasted with the fastest method for Python 2, which is + concatenation on my computer; and that takes 0.203 µs with 8-bit strings, and 0.259 µs if the strings are all Unicode.

No comments:

Post a Comment