比namedtuple更快的选择。

plain_obj的Python项目详细描述


https://travis-ci.org/suzaku/plain_obj.svg?branch=masterhttps://img.shields.io/pypi/v/plain_obj.svg

比namedtuple更快的选择。

基本用法

创建

importplain_objConfig=plain_obj.new_type('Config','is_debug, skips_dist, run_tests')config=Config(True,False,True)ifconfig.is_debug:print("This is a verbose debugging message.")

做一个dict

config.as_dict()

拆包

is_debug,_,run_tests=config
Sponsor

何时使用plain_obj而不是namedtuple

当更快的创建时间对您很重要时。

比较python 2.7中的plain_objnamedtuple

In[3]:%timeitcollections.namedtuple('Point',['x','y','z'])1000loops,bestof3:338µsperloopIn[4]:%timeitplain_obj.new_type('Point',['x','y','z'])10000loops,bestof3:97.8µsperloopIn[5]:Point=collections.namedtuple('Point',['x','y','z'])In[6]:NewPoint=plain_obj.new_type('Point',['x','y','z'])In[7]:%timeitPoint(1,2,3)Theslowestruntook7.99timeslongerthanthefastest.Thiscouldmeanthatanintermediateresultisbeingcached.1000000loops,bestof3:507nsperloopIn[8]:%timeitNewPoint(1,2,3)Theslowestruntook6.70timeslongerthanthefastest.Thiscouldmeanthatanintermediateresultisbeingcached.1000000loops,bestof3:462nsperloopIn[9]:p=Point(1,2,3)In[10]:new_p=NewPoint(1,2,3)In[11]:%timeitp.x,p.y,p.zTheslowestruntook9.92timeslongerthanthefastest.Thiscouldmeanthatanintermediateresultisbeingcached.1000000loops,bestof3:408nsperloopIn[12]:%timeitnew_p.x,new_p.y,new_p.zTheslowestruntook11.70timeslongerthanthefastest.Thiscouldmeanthatanintermediateresultisbeingcached.10000000loops,bestof3:163nsperloop

比较python 3.6中的plain_objnamedtuple

In[3]:%timeitcollections.namedtuple('Point',['x','y','z'])382µs±3.82µsperloop(mean±std.dev.of7runs,1000loopseach)In[4]:%timeitplain_obj.new_type('Point',['x','y','z'])53.5µs±1.2µsperloop(mean±std.dev.of7runs,10000loopseach)In[5]:Point=collections.namedtuple('Point',['x','y','z'])In[6]:NewPoint=plain_obj.new_type('Point',['x','y','z'])In[7]:%timeitPoint(1,2,3)521ns±2.5nsperloop(mean±std.dev.of7runs,1000000loopseach)In[8]:%timeitNewPoint(1,2,3)438ns±5.53nsperloop(mean±std.dev.of7runs,1000000loopseach)In[9]:p=Point(1,2,3)In[10]:new_p=NewPoint(1,2,3)In[11]:%timeitp.x,p.y,p.z282ns±2.52nsperloop(mean±std.dev.of7runs,1000000loopseach)In[12]:%timeitnew_p.x,new_p.y,new_p.z148ns±1.7nsperloop(mean±std.dev.of7runs,10000000loopseach)

如您所见,它在所有情况下都更快,包括type creationobject instantiationattribute access

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
graph Java自己生成类图   java MouseMotionListener:鼠标和触控板给出不同的结果   java解析清单条目的正确方法是什么。jar中的mf文件?   java如何创建带有半透明色块的透明gif/png图像?   java应用内计费V3:跨设备同步购买   java Spring数据JPA注入失败BeanCreationException:无法自动连接字段   Java数据结构维护插入顺序和重复值   java无法在VSCode中设置JavaFX   java中数据字段初始化的类顺序   java如何使用ClientBuilder为Rest Post Api多部分编写集成测试   JUnit测试divide()方法的java正确方法   java将消息标记为接收前已读   Java ArrayList调用扩展对象函数   java Android:只使用GCM的TCP/IPServer   Java如何将xls数据转换为txt文件   编译为Jar文件后未找到java类   java返回子字符串的所有匹配项   java Get json用户_timeline api twitter 1.1