我使用的是带有8GB内存和1.7GHz Core i5的Python 2.7.5 @ Mac OS X 10.9.3.我测试了时间消耗如下.
d = {i:i*2 for i in xrange(10**7*3)} #WARNING: it takes time and consumes a lot of RAM
%time for k in d: k,d[k]
CPU times: user 6.22 s, sys: 10.1 ms, total: 6.23 s
Wall time: 6.23 s
%time for k,v in d.iteritems(): k, v
CPU times: user 7.67 s, sys: 27.1 ms, total: 7.7 s
Wall time: 7.69 s
Run Code Online (Sandbox Code Playgroud)
似乎iteritems更慢.我想知道iteritems比直接访问dict有什么好处.
更新:获得更准确的时间配置文件
In [23]: %timeit -n 5 for k in d: …
Run Code Online (Sandbox Code Playgroud) 我有类似unicode的字符串,但有斜线转义.例如,'\\u000D'
.我需要将它们解码为普通字符串.上面的例子应该被转换成'\r'
其'\u000D'
对应.
我认为主要目的__slots__
是通过允许显式指定属性来节省内存使用量,而不是允许__dict__
在实例上动态分配属性。所以我以某种方式理解为什么__dict__
在使用时默认删除__slots__
。但为什么它同时__weakref__
默认删除呢?
参考: https: //docs.python.org/3/reference/datamodel.html#slots