在类中定义__slot__属性来限制实例的属性字段,在创建大量对象的场合可以减少内存占用。

创建大量对象是内存占用对比:

  1. 类中不使用__slot__
class MySlot:def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c @profile()
def main():
myObj_list = list()
for i in range(50000):
myObj = MySlot(i, i, i)
myObj_list.append(myObj)

执行结果:

Line # Mem usage Increment Line Contents
================================================
401 39.7 MiB 39.7 MiB @profile()
402 def main():
403 39.7 MiB 0.0 MiB myObj_list = list()
404 49.9 MiB 0.0 MiB for i in range(50000):
405 49.9 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 49.9 MiB 0.4 MiB myObj_list.append(myObj)

占用内存约10M

  1. 类中使用__slot__
class MySlot:
__slots__ = ('a', 'b', 'c')
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c @profile()
def main():
myObj_list = list()
for i in range(50000):
myObj = MySlot(i, i, i)
myObj_list.append(myObj)

执行结果:

Line # Mem usage Increment Line Contents
================================================
401 40.3 MiB 40.3 MiB @profile()
402 def main():
403 40.3 MiB 0.0 MiB myObj_list = list()
404 45.7 MiB 0.0 MiB for i in range(50000):
405 45.7 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 45.7 MiB 0.3 MiB myObj_list.append(myObj)

占用内存约5M

  1. 说明

  __slot__限制了属性值,添加__slot__元组之外的属性会报错!

  __slot__限制的是实例属性的添加,不限制类属性的添加!

最新文章

  1. Linux下安装maven
  2. Hibernate里save(),saveOrUpdate(),merge(),update()的区别
  3. Java编程中-servlet
  4. asp.net mvc 在View中获取Url参数的值
  5. Could not find class XXX referenced from method XXX.<YYY>
  6. ionic之AngularJS扩展 移动开发(视图导航一)
  7. 二、break,continue区别
  8. java基础知识回顾之java Thread类学习(六)--java多线程同步函数用的锁
  9. VS2003.NET在文件中查找卡死
  10. Cocos2d-x 学习之路------(CCCallfunc 系列)
  11. LeetCodeOJ. Longest Common Prefix
  12. Linux文件基本操作
  13. DP思想笔记
  14. 插入排序专题 直接插入 折半 希尔shell
  15. linux c 输出信息到console
  16. 【zheng环境准备】安装redis
  17. 理解JVM之垃圾收集器概述
  18. 8.5 正睿暑期集训营 Day2
  19. IntelliJ IDEA 2017版 springloaded实现热部署
  20. el表达式取值优先级

热门文章

  1. Hello Kotlin! Kotlin学习资料
  2. 使用maven如何生成源代码的jar包
  3. VS Project Property Manage
  4. Visual Studio Code - 在 JS 源码(TS、压缩前代码)上使用断点
  5. 用Vue来实现音乐播放器(五):路由配置+顶部导航栏组件开发
  6. 搭建python-flask开发环境
  7. Powershell指令集_1
  8. Week4 - 500.Keyboard Row & 557.Reverse Words in a String III
  9. Python写一个自动点餐程序
  10. python 字典zip使用