Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
wjk2a1 Avatar asked Aug 02 '16 13:08

wjk2a1


People also ask

What are the benefits of using the format method instead of string concatenation?

The main advantages of using format(…) are that the string can be a bit easier to produce and read as in particular in the second example, and that we don't have to explicitly convert all non-string variables to strings with str(…).

Is string format faster than concatenation Java?

Therefore, concatenation is much faster than String.

Is it good to use string format?

tl;dr. Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.

Is string format faster than concatenation C#?

I have taken a look at String. Format (using Reflector) and it actually creates a StringBuilder then calls AppendFormat on it. So it is quicker than concat for multiple stirngs.


1 Answers

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:

Python 3.7.2 (default, Jan  3 2019, 02:55:40) IPython 5.8.0 Intel(R) Core(TM) i5-4590T CPU @ 2.00GHz  In [1]: %timeit root = "sample"; output = "output"; path = "{}/{}".format(root, output) The slowest run took 12.44 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 5: 223 ns per loop  In [2]: %timeit root = "sample"; output = "output"; path = root + '/' + output The slowest run took 13.82 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 5: 101 ns per loop  In [3]: %timeit root = "sample"; output = "output"; path = "%s/%s" % (root, output) The slowest run took 27.97 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 5: 155 ns per loop  In [4]: %timeit root = "sample"; output = "output"; path = f"{root}/{output}" The slowest run took 19.52 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 5: 77.8 ns per loop 
like image 59
kay Avatar answered Sep 24 '22 02:09

kay