Python: Do (explicit) string parameters hurt performance?

心不动则不痛 提交于 2019-12-02 03:31:55

The string is passed (by reference) each time, but the overhead is way too tiny to really affect performance unless it's in a super-tight loop.

this is an implementation detail of CPython, and may not apply to other pythons but yes, in many cases in a compiled module, a constant string will reference the same object, minimizing the overhead.

In general, even if it didn't, you really shouldn't worry about it, as it's probably imperceptibly tiny compared to other things going on.

However, here's a little interesting piece of code:

>>> def somefunc(x):
...    print id(x) # prints the memory address of object pointed to by x
... 
>>> 
>>> def test():
...    somefunc("hello")
... 
>>> test()
134900896
>>> test()
134900896 # Hooray, like expected, it's the same object id
>>> somefunc("h" + "ello")
134900896  # Whoa, how'd that work?

What's happening here is that python keeps a global string lookup and in many cases, even when you concatenate two strings, you will get the same object if the values match up.

Note that this is an implementation detail, and you should NOT rely on it, as strings from any of: files, sockets, databases, string slicing, regex, or really any C module are not guaranteed to have this property. But it is interesting nonetheless.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!