简体   繁体   中英

Is %s faster than + for python string concatentation

Understanding that using the str.join operator is the 'chosen' way to concatenate strings in python, I was wandering where in the pecking order operations of the type:

 "%s %s" % (first_name, last_name)

would fit. Are they faster or slower than using + ?

Let's see:

>>> first_name = 'Test'
>>> last_name = 'Name'

>>> %timeit "%s %s" % (first_name, last_name)
10000000 loops, best of 3: 168 ns per loop

>>> %timeit ' '.join((first_name, last_name))
10000000 loops, best of 3: 157 ns per loop

>>> %timeit first_name + ' ' + last_name
10000000 loops, best of 3: 103 ns per loop

And if you cache the tuple:

>>> name_tuple = (first_name, last_name)

>>> %timeit "%s %s" % name_tuple
10000000 loops, best of 3: 125 ns per loop

>>> %timeit ' '.join(name_tuple)
10000000 loops, best of 3: 114 ns per loop

Answer: No.

在此处输入图片说明

In [1]: tup = 'hello', 'world'

In [2]: timeit 'hello' + 'world'
10000000 loops, best of 3: 20.2 ns per loop

In [3]: timeit tup[0] + tup[1]
10000000 loops, best of 3: 129 ns per loop

In [4]: timeit '{}{}'.format('hello', 'world')
1000000 loops, best of 3: 285 ns per loop

In [5]: timeit '{}{}'.format(*tup)
1000000 loops, best of 3: 281 ns per loop

In [6]: timeit '%s%s' % ('hello', 'world')
10000000 loops, best of 3: 122 ns per loop

In [7]: timeit '%s%s' % tup
10000000 loops, best of 3: 135 ns per loop

In [8]: timeit ''.join(['hello', 'world'])
1000000 loops, best of 3: 210 ns per loop

In [9]: timeit ''.join(tup)
10000000 loops, best of 3: 121 ns per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM