wjk2a1 wjk2a1 - 4 months ago 7
Python Question

Format strings vs concatenation

I see many people using format strings like this:

root = "sample"
output = "output"
path = "{}/{}".format(root, output)


Instead of simply concatenating strings like this:

path = root + '/' + output


Do format strings have better performance or is this just for looks?

Kay Kay
Answer

It's just for the looks. You can see at one glance what the format is. Many of us like readability better than micro-optimization.

Let's see what IPython's %timeit says:

In [1]: %timeit root = "sample"; output = "output"; path = "{}/{}".format(root, output)
The slowest run took 33.07 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 209 ns per loop

In [2]: %timeit root = "sample"; output = "output"; path = root + '/' + output
The slowest run took 19.63 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 97.2 ns per loop

In [3]: %timeit root = "sample"; output = "output"; path = "%s/%s" % (root, output)
The slowest run took 19.28 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 148 ns per loop