bb.
bb.

Reputation: 149

Python: Do (explicit) string parameters hurt performance?

Suppose some function that always gets some parameter s that it does not use.

def someFunc(s):
  # do something _not_ using s, for example
  a=1

now consider this call

someFunc("the unused string")

which gives a string as a parameter that is not built during runtime but compiled straight into the binary (hope thats right).

The question is: when calling someFunc this way for, say, severalthousand times the reference to "the unused string" is always passed but does that slow the program down?

in my naive thoughts i'd say the reference to "the unused string" is 'constant' and available in O(1) when a call to someFunc occurs. So i'd say 'no, that does not hurt performance'.

Same question as before: "Am I right?"

thanks for some :-)

Upvotes: 1

Views: 569

Answers (2)

Crast
Crast

Reputation: 16326

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.

Upvotes: 2

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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.

Upvotes: 2

Related Questions