python在类中使用__slot__属性
在类中定义__slot__属性来限制实例的属性字段,在创建大量对象的场合可以减少内存占用。
创建大量对象是内存占用对比:
- 类中不使用__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
- 类中使用__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
- 说明
__slot__限制了属性值,添加__slot__元组之外的属性会报错!
__slot__限制的是实例属性的添加,不限制类属性的添加!
最新文章
- Linux下安装maven
- Hibernate里save(),saveOrUpdate(),merge(),update()的区别
- Java编程中-servlet
- asp.net mvc 在View中获取Url参数的值
- Could not find class XXX referenced from method XXX.<;YYY>;
- ionic之AngularJS扩展 移动开发(视图导航一)
- 二、break,continue区别
- java基础知识回顾之java Thread类学习(六)--java多线程同步函数用的锁
- VS2003.NET在文件中查找卡死
- Cocos2d-x 学习之路------(CCCallfunc 系列)
- LeetCodeOJ. Longest Common Prefix
- Linux文件基本操作
- DP思想笔记
- 插入排序专题 直接插入 折半 希尔shell
- linux c 输出信息到console
- 【zheng环境准备】安装redis
- 理解JVM之垃圾收集器概述
- 8.5 正睿暑期集训营 Day2
- IntelliJ IDEA 2017版 springloaded实现热部署
- el表达式取值优先级
热门文章
- Hello Kotlin! Kotlin学习资料
- 使用maven如何生成源代码的jar包
- VS Project Property Manage
- Visual Studio Code - 在 JS 源码(TS、压缩前代码)上使用断点
- 用Vue来实现音乐播放器(五):路由配置+顶部导航栏组件开发
- 搭建python-flask开发环境
- Powershell指令集_1
- Week4 - 500.Keyboard Row &; 557.Reverse Words in a String III
- Python写一个自动点餐程序
- python 字典zip使用