Python 中更节省内存的结构表示?
More memory-efficient struct representation in Python?
我有一个我正在尝试创建的经典 Point
结构的等价物。
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
但是,我只需要有限的功能(通过属性名访问)和 none 命名元组的额外开销(例如长度、索引访问、__contains__
等)此外,我的用例还具有 Point.x
和 Point.y
的固定类型,因此可能还有依赖于静态类型保证的进一步破解。
有内存开销更少的东西吗?也许 ctypes
或 Cython
解决方案?
我想,创建 Cython 扩展将是减少内存影响的最简单方法。 Cython 扩展类型的属性直接存储在对象的 C 结构中,属性集在编译时固定(很像 Python 的 __slots__
)。
cdef class Point:
cdef readonly double x, y # C-level attributes
def __init__(self, double x, double y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({}, {})'.format(self.x, self.y)
对于 Cython 不是选项的情况
有一种方法可以减少内存占用:
>>> from recordclass import dataobject
>>> class Point(dataobject):
... x:int
... y:int
>>>
>>> p = Point(1,2)
>>> class Point2(object):
.... __slots__ = ('x', 'y')
.... def __init__(self, x, y):
.... self.x = x
.... self.y = y
>>>
>>> p2 = Point2(1,2)
>>> from sys import getsizeof as sizeof
>>> sizeof(p2) - sizeof(p)
24
差异等于用于循环垃圾收集支持的额外 space 的大小。
我有一个我正在尝试创建的经典 Point
结构的等价物。
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
但是,我只需要有限的功能(通过属性名访问)和 none 命名元组的额外开销(例如长度、索引访问、__contains__
等)此外,我的用例还具有 Point.x
和 Point.y
的固定类型,因此可能还有依赖于静态类型保证的进一步破解。
有内存开销更少的东西吗?也许 ctypes
或 Cython
解决方案?
我想,创建 Cython 扩展将是减少内存影响的最简单方法。 Cython 扩展类型的属性直接存储在对象的 C 结构中,属性集在编译时固定(很像 Python 的 __slots__
)。
cdef class Point:
cdef readonly double x, y # C-level attributes
def __init__(self, double x, double y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({}, {})'.format(self.x, self.y)
对于 Cython 不是选项的情况
有一种方法可以减少内存占用:
>>> from recordclass import dataobject
>>> class Point(dataobject):
... x:int
... y:int
>>>
>>> p = Point(1,2)
>>> class Point2(object):
.... __slots__ = ('x', 'y')
.... def __init__(self, x, y):
.... self.x = x
.... self.y = y
>>>
>>> p2 = Point2(1,2)
>>> from sys import getsizeof as sizeof
>>> sizeof(p2) - sizeof(p)
24
差异等于用于循环垃圾收集支持的额外 space 的大小。