格式化字符串与连接 [英] Format strings vs concatenation

查看:66
本文介绍了格式化字符串与连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多人使用这样的格式字符串:

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?

推荐答案

这只是为了外观.一看就知道是什么格式.我们中的许多人更喜欢可读性而不是微优化.

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.

让我们看看 IPython 的 %timeit 怎么说:

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

这篇关于格式化字符串与连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆