字典 vs 对象 - 哪个更高效,为什么?

150

在Python中,从内存使用和CPU消耗的角度来看,字典或对象哪个更有效率?

背景: 我需要将大量数据加载到Python中。我创建了一个仅用于字段容器的对象。创建4M实例并将它们放入字典中约需10分钟和约6GB的内存。一旦字典准备好,访问它就是眨眼之间的事情。

示例: 为了检查性能,我编写了两个简单的程序,执行相同的操作 - 其中一个使用对象,另一个使用字典:

对象(执行时间约为18秒):

class Obj(object):
  def __init__(self, i):
    self.i = i
    self.l = []
all = {}
for i in range(1000000):
  all[i] = Obj(i)

字典(执行时间约为12秒):

all = {}
for i in range(1000000):
  o = {}
  o['i'] = i
  o['l'] = []
  all[i] = o

问题: 我是做错了什么吗?还是字典确实比对象更快?如果确实如此,能否有人解释一下原因?


11
当生成大序列时,建议使用xrange而不是range。当然,因为你要处理执行时间的秒数,所以这不会有太大的差别,但还是养成好习惯。 - Xiong Chiamiov
4
除非它是Python3,否则不行。 - Barney Szabolcs
8个回答

182

您尝试使用__slots__了吗?

根据文档

默认情况下,旧式类和新式类的实例都有用于属性存储的字典。这会浪费仅具有极少量实例变量的对象的空间。创建大量实例时,空间消耗可能会变得非常严重。

可以通过在新式类定义中定义__slots__来覆盖默认行为。 __slots__声明采用一系列实例变量并为每个实例保留足够的空间以容纳每个变量的值。节省空间因为不为每个实例创建__dict__

那么这样做除了节省内存外,还能节省时间吗?

在我的计算机上比较三种方法:

test_slots.py:

class Obj(object):
  __slots__ = ('i', 'l')
  def __init__(self, i):
    self.i = i
    self.l = []
all = {}
for i in range(1000000):
  all[i] = Obj(i)

test_obj.py:

class Obj(object):
  def __init__(self, i):
    self.i = i
    self.l = []
all = {}
for i in range(1000000):
  all[i] = Obj(i)

test_dict.py:

->

test_dict.py:

all = {}
for i in range(1000000):
  o = {}
  o['i'] = i
  o['l'] = []
  all[i] = o

test_namedtuple.py(在2.6中支持):

import collections

Obj = collections.namedtuple('Obj', 'i l')

all = {}
for i in range(1000000):
  all[i] = Obj(i, [])

运行基准测试(使用CPython 2.5):

$ lshw | grep product | head -n 1
          product: Intel(R) Pentium(R) M processor 1.60GHz
$ python --version
Python 2.5
$ time python test_obj.py && time python test_dict.py && time python test_slots.py 

real    0m27.398s (using 'normal' object)
real    0m16.747s (using __dict__)
real    0m11.777s (using __slots__)

使用 CPython 2.6.2,包括命名元组测试:

$ python --version
Python 2.6.2
$ time python test_obj.py && time python test_dict.py && time python test_slots.py && time python test_namedtuple.py 

real    0m27.197s (using 'normal' object)
real    0m17.657s (using __dict__)
real    0m12.249s (using __slots__)
real    0m12.262s (using namedtuple)

所以,使用__slots__是一种性能优化(并不意外)。使用命名元组与__slots__具有类似的性能。


4
太好了 - 谢谢!我在我的机器上尝试了同样的方法 - 带有 slots 的对象是最有效的方法(我得到了约7秒的运行时间) 。 - tkokoszka
6
还有一种叫做命名元组的数据结构,http://docs.python.org/library/collections.html#collections.namedtuple ,它是一个使用槽(slot)来创建对象的类工厂。它更加整洁,甚至可能更加优化。 - Jochen Ritzel
1
我也测试了命名元组,并更新了答案的结果。 - codeape
1
我运行了你的代码几次,惊讶地发现我的结果与你的不同 - slots=3秒 obj=11秒 dict=12秒 namedtuple=16秒。我在Win7 64位上使用CPython 2.6.6。 - Jonathan Livni
1
为什么使用普通对象比使用 dict 慢得多,如果在底层,普通对象也是使用字典的呢? - Detached Laconian
显示剩余3条评论

17

对象中的属性访问在幕后使用了字典访问 - 因此使用属性访问会增加额外的开销。此外,在对象的情况下,由于例如额外的内存分配和代码执行(例如__init__方法),您将承担额外的开销。

在您的代码中,如果o是一个Obj实例,则o.attr等同于o.__dict__['attr']并额外增加一小部分开销。


你测试过这个吗?o.__dict__["attr"]会多出一些开销,需要额外的字节码操作;obj.attr更快。(当然属性访问不会比订阅访问慢——这是一个关键的、经过大量优化的代码路径。) - Glenn Maynard
2
显然,如果你实际上执行 o.dict["attr"],速度会变慢 - 我只是想说它相当于那样,而不是确切地以那种方式实现。我想我的措辞没有表达清楚。我还提到了其他因素,如内存分配、构造函数调用时间等。 - Vinay Sajip
2
11年后的Python3最新版本是否仍然如此? - matanster

11

您是否考虑过使用namedtuple?(Python 2.4/2.5 的链接)

这是一种表示结构化数据的新标准方式,它给您提供了元组的性能和类的便利性。

与字典相比,它唯一的缺点是(像元组一样)创建后不能更改属性。


10

这是@hughdbrown针对Python 3.6.1的答案副本,我将计数扩大了5倍,并添加了一些代码来测试每次运行结束时Python进程的内存占用。

在投票者开始之前,请注意,此计算对象大小的方法不准确。

from datetime import datetime
import os
import psutil

process = psutil.Process(os.getpid())


ITER_COUNT = 1000 * 1000 * 5

RESULT=None

def makeL(i):
    # Use this line to negate the effect of the strings on the test 
    # return "Python is smart and will only create one string with this line"

    # Use this if you want to see the difference with 5 million unique strings
    return "This is a sample string %s" % i

def timeit(method):
    def timed(*args, **kw):
        global RESULT
        s = datetime.now()
        RESULT = method(*args, **kw)
        e = datetime.now()

        sizeMb = process.memory_info().rss / 1024 / 1024
        sizeMbStr = "{0:,}".format(round(sizeMb, 2))

        print('Time Taken = %s, \t%s, \tSize = %s' % (e - s, method.__name__, sizeMbStr))

    return timed

class Obj(object):
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

class SlotObj(object):
    __slots__ = ('i', 'l')
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

from collections import namedtuple
NT = namedtuple("NT", ["i", 'l'])

@timeit
def profile_dict_of_nt():
    return [NT(i=i, l=makeL(i)) for i in range(ITER_COUNT)]

@timeit
def profile_list_of_nt():
    return dict((i, NT(i=i, l=makeL(i))) for i in range(ITER_COUNT))

@timeit
def profile_dict_of_dict():
    return dict((i, {'i': i, 'l': makeL(i)}) for i in range(ITER_COUNT))

@timeit
def profile_list_of_dict():
    return [{'i': i, 'l': makeL(i)} for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_obj():
    return dict((i, Obj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_obj():
    return [Obj(i) for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_slot():
    return dict((i, SlotObj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_slot():
    return [SlotObj(i) for i in range(ITER_COUNT)]

profile_dict_of_nt()
profile_list_of_nt()
profile_dict_of_dict()
profile_list_of_dict()
profile_dict_of_obj()
profile_list_of_obj()
profile_dict_of_slot()
profile_list_of_slot()

这是我的结果。
Time Taken = 0:00:07.018720,    provile_dict_of_nt,     Size = 951.83
Time Taken = 0:00:07.716197,    provile_list_of_nt,     Size = 1,084.75
Time Taken = 0:00:03.237139,    profile_dict_of_dict,   Size = 1,926.29
Time Taken = 0:00:02.770469,    profile_list_of_dict,   Size = 1,778.58
Time Taken = 0:00:07.961045,    profile_dict_of_obj,    Size = 1,537.64
Time Taken = 0:00:05.899573,    profile_list_of_obj,    Size = 1,458.05
Time Taken = 0:00:06.567684,    profile_dict_of_slot,   Size = 1,035.65
Time Taken = 0:00:04.925101,    profile_list_of_slot,   Size = 887.49

我的结论是:
  1. 插槽在内存占用和速度上表现最好。
  2. 字典是最快的,但使用的内存最多。

伙计,你应该把这个变成一个问题。我也在自己的电脑上运行了一下,只是为了确保(我没有安装psutil,所以我把那部分拿掉了)。无论如何,这让我感到困惑,意味着原始问题没有完全得到回答。 所有其他答案都像“namedtuple很棒”和“使用__slots__”,显然每次使用全新的dict对象比它们更快?我猜dicts真的被很好地优化了? - Multihunter
1
这似乎是makeL函数返回字符串的结果。如果您返回一个空列表,那么结果大致与python2中hughdbrown的结果相匹配。除了namedtuples始终比SlotObj慢 :( - Multihunter
可能存在一个小问题:由于Python中的字符串被缓存,因此makeL在每个'@timeit'轮中的速度可能不同 - 但也许我是错的。 - Barney Szabolcs
@BarnabasSzabolcs应该每次创建一个新的字符串,因为它需要替换值"这是一个示例字符串%s" % i - Jarrod Chesney
是的,在循环内是正确的,但在第二个测试中,i再次从0开始。 - Barney Szabolcs

4
from datetime import datetime

ITER_COUNT = 1000 * 1000

def timeit(method):
    def timed(*args, **kw):
        s = datetime.now()
        result = method(*args, **kw)
        e = datetime.now()

        print method.__name__, '(%r, %r)' % (args, kw), e - s
        return result
    return timed

class Obj(object):
    def __init__(self, i):
       self.i = i
       self.l = []

class SlotObj(object):
    __slots__ = ('i', 'l')
    def __init__(self, i):
       self.i = i
       self.l = []

@timeit
def profile_dict_of_dict():
    return dict((i, {'i': i, 'l': []}) for i in xrange(ITER_COUNT))

@timeit
def profile_list_of_dict():
    return [{'i': i, 'l': []} for i in xrange(ITER_COUNT)]

@timeit
def profile_dict_of_obj():
    return dict((i, Obj(i)) for i in xrange(ITER_COUNT))

@timeit
def profile_list_of_obj():
    return [Obj(i) for i in xrange(ITER_COUNT)]

@timeit
def profile_dict_of_slotobj():
    return dict((i, SlotObj(i)) for i in xrange(ITER_COUNT))

@timeit
def profile_list_of_slotobj():
    return [SlotObj(i) for i in xrange(ITER_COUNT)]

if __name__ == '__main__':
    profile_dict_of_dict()
    profile_list_of_dict()
    profile_dict_of_obj()
    profile_list_of_obj()
    profile_dict_of_slotobj()
    profile_list_of_slotobj()

结果:

hbrown@hbrown-lpt:~$ python ~/Dropbox/src/StackOverflow/1336791.py 
profile_dict_of_dict ((), {}) 0:00:08.228094
profile_list_of_dict ((), {}) 0:00:06.040870
profile_dict_of_obj ((), {}) 0:00:11.481681
profile_list_of_obj ((), {}) 0:00:10.893125
profile_dict_of_slotobj ((), {}) 0:00:06.381897
profile_list_of_slotobj ((), {}) 0:00:05.860749

3

没有问题。
你有数据,没有其他属性(没有方法,什么都没有)。因此你有一个数据容器(在这种情况下是一个字典)。

我通常更喜欢从数据建模的角度思考。如果有一些巨大的性能问题,那么我可以放弃抽象中的某些东西,但只有在非常好的理由下才能这样做。
编程就是管理复杂性,并且保持正确的抽象往往是实现这种结果的最有用的方法之一。

关于对象速度较慢的原因,我认为你的测量不正确。
你在for循环内执行了太少的赋值操作,因此你看到的是实例化字典(内置对象)和“自定义”对象所需的不同时间。尽管从语言的角度来看它们是相同的,但它们有着非常不同的实现。
之后,赋值时间对两者应该几乎相同,因为最终成员都在字典中维护。


0

如果数据结构不应该包含引用循环,那么使用recordclass库可以通过另一种方式来减少内存使用。

让我们比较两个类:

class DataItem:
    __slots__ = ('name', 'age', 'address')
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

并且

$ pip install recordclass

>>> from recordclass import make_dataclass
>>> DataItem2 = make_dataclass('DataItem', 'name age address')
>>> inst = DataItem('Mike', 10, 'Cherry Street 15')
>>> inst2 = DataItem2('Mike', 10, 'Cherry Street 15')
>>> print(inst2)
DataItem(name='Mike', age=10, address='Cherry Street 15')
>>> print(sys.getsizeof(inst), sys.getsizeof(inst2))
64 40

这是因为基于dataobject的子类不支持循环垃圾回收,而在这种情况下也不需要。


0
这是我对@Jarrod-Chesney的非常好的脚本进行测试的结果。 为了比较,我还使用"range"替换为"xrange"在python2中运行它。
出于好奇,我还添加了类似的OrderedDict(ordict)测试以进行比较。
Python 3.6.9:
Time Taken = 0:00:04.971369,    profile_dict_of_nt,     Size = 944.27
Time Taken = 0:00:05.743104,    profile_list_of_nt,     Size = 1,066.93
Time Taken = 0:00:02.524507,    profile_dict_of_dict,   Size = 1,920.35
Time Taken = 0:00:02.123801,    profile_list_of_dict,   Size = 1,760.9
Time Taken = 0:00:05.374294,    profile_dict_of_obj,    Size = 1,532.12
Time Taken = 0:00:04.517245,    profile_list_of_obj,    Size = 1,441.04
Time Taken = 0:00:04.590298,    profile_dict_of_slot,   Size = 1,030.09
Time Taken = 0:00:04.197425,    profile_list_of_slot,   Size = 870.67

Time Taken = 0:00:08.833653,    profile_ordict_of_ordict, Size = 3,045.52
Time Taken = 0:00:11.539006,    profile_list_of_ordict, Size = 2,722.34
Time Taken = 0:00:06.428105,    profile_ordict_of_obj,  Size = 1,799.29
Time Taken = 0:00:05.559248,    profile_ordict_of_slot, Size = 1,257.75

Python 2.7.15+:

Time Taken = 0:00:05.193900,    profile_dict_of_nt,     Size = 906.0
Time Taken = 0:00:05.860978,    profile_list_of_nt,     Size = 1,177.0
Time Taken = 0:00:02.370905,    profile_dict_of_dict,   Size = 2,228.0
Time Taken = 0:00:02.100117,    profile_list_of_dict,   Size = 2,036.0
Time Taken = 0:00:08.353666,    profile_dict_of_obj,    Size = 2,493.0
Time Taken = 0:00:07.441747,    profile_list_of_obj,    Size = 2,337.0
Time Taken = 0:00:06.118018,    profile_dict_of_slot,   Size = 1,117.0
Time Taken = 0:00:04.654888,    profile_list_of_slot,   Size = 964.0

Time Taken = 0:00:59.576874,    profile_ordict_of_ordict, Size = 7,427.0
Time Taken = 0:10:25.679784,    profile_list_of_ordict, Size = 11,305.0
Time Taken = 0:05:47.289230,    profile_ordict_of_obj,  Size = 11,477.0
Time Taken = 0:00:51.485756,    profile_ordict_of_slot, Size = 11,193.0

因此,在两个主要版本上,@Jarrod-Chesney的结论仍然看起来不错。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接