5.2. Case Study: Str Concat

5.2.1. Environment

  • Date: 2024-07-11

  • Python: 3.12.4

  • IPython: 8.26.0

  • System: macOS 14.5

  • Computer: MacBook M3 Max

  • CPU: 16 cores (12 performance and 4 efficiency) / 3nm

  • RAM: 128 GB RAM LPDDR5

5.2.2. SetUp

>>> firstname = 'Mark'
>>> lastname = 'Watney'

5.2.3. F-string

>>> 
... %%timeit -r 10_000 -n 10_000
... f'{firstname} {lastname}'
...
37.4 ns ± 3.34 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)

5.2.4. str.format()

>>> 
... %%timeit -r 10_000 -n 10_000
... '{} {}'.format(firstname, lastname)
...
83.2 ns ± 3.9 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)
>>> 
... %%timeit -r 10_000 -n 10_000
... '{0} {1}'.format(firstname, lastname)
...
91.5 ns ± 5.06 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)
>>> 
... %%timeit -r 10_000 -n 10_000
... '{fname} {lname}'.format(fname=firstname, lname=lastname)
...
169 ns ± 6.23 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)

5.2.5. Add Operator

>>> 
... %%timeit -r 10_000 -n 10_000
... firstname + ' ' + lastname
...
39.3 ns ± 2.89 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)

5.2.6. Mod Operator

>>> 
... %%timeit -r 10_000 -n 10_000
... '%s %s' % (firstname, lastname)
...
46.8 ns ± 3.3 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)
>>> 
... %%timeit -r 10_000 -n 10_000
... '%(fname)s %(lname)s' % {'fname': firstname, 'lname': lastname}
...
139 ns ± 5.55 ns per loop (mean ± std. dev. of 10000 runs, 10,000 loops each)