开发者

If you add the same string to two different lists or collections in Python, are you using twice the memory?

For instance if 开发者_开发百科you add the same string to a dict and a list?


A copy of the string is not put into both, they just both point to the one string.


Strings are immutable and are never copied. Indeed, even if you manually request a copy, you'll still get the same object:

>>> import copy
>>> s = "abc"
>>> t = copy.copy(s)
>>> u = copy.deepcopy(s)
>>> id(s), id(t), id(u)
(139730866789424, 139730866789424, 139730866789424)
>>> s is t, s is u
(True, True)


If it's the same string, only one copy of it exists (and two references to that single object). Two strings that are equal on the other hand can very well end up as two copies, depending on what optimizations the compiler is able to do to avoid the duplication.

Consider, for example (Python 2.6 or earlier -- not sure what further optimizations may be added in the future):

>>> def f1(s, d, l):
...   d['z'] = s
...   l.append(s)
... 
>>> d={}
>>> l=[]
>>> f1('ciao', d, l)
>>> d['z'] is l[0]
True
>>> def f1(s, d, l):
...   d['z'] = s + 'zap'
...   l.append(s + 'zap')
... 
>>> f1('ciao', d, l)
>>> d['z'] is l[1]
False
>>> d['z'] == l[1]
True
>>> 

The first one's a no-brainer -- clearly the same object. The second one involves two equal strings -- if the compiler was smarter it could have detected the equality and optimized things to avoid the duplication, but, in general, Python's compiler is tuned to compile very fast, not to spend much time optimizing things.


No. If you have a single string object:

s = "Some string."

And you add it to, say, a dict and a list:

d = {"akey": s}
l = [s]

Then d["akey"] and l[0] will point to the same string object as s, not two different objects with the content "Some string.".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜