在Python中访问类变量的性能 [英] Performance of accessing class variables in Python

查看:96
本文介绍了在Python中访问类变量的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在使用以下方法访问同一个类的方法中的类变量(字典) 时,性能是否存在差异?

I wonder if there is any difference in performance when accessing a class variable (a dict) inside a method of the same class using:

self.class_variable_dict.add(some_key, some_value)

ClassName.class_variable_dict.add(some_key, some_value)

很明显,只要没有名称相同的实例变量,两者都可以工作,但是是否有任何理由/用例值得我们优先考虑?

obviously, both will work as long as there is no instance variable with the same name, but is there any reason/use case for which we should prefer one over the other?

推荐答案

通过ClassName而不是通过self进行访问将更快 ,因为如果通过self进行访问它必须首先检查实例名称空间.但是,除非您有概要分析的信息表明确实如此,否则我认为差异根本不会很大.

Accessing it via ClassName rather than via self will be slightly faster, since if you access it via self it must first check the instance namespace. But I don't expect the difference to be at all significant, unless you have profiling information to suggest that it is.

因此,我建议您使用任何您认为较容易理解/理解的人.

So I would recommend using whichever one you think is easier to read/understand as a human.

在语义上,只有当class_variable_dict变量被遮盖在某处时,它们才会有所不同-特别是(a)self定义了相同名称的变量;或(b)selfClassName子类的实例,并且该子类(或其基类之一仍然是ClassName的子类)定义了一个同名变量.如果这些都不是真的,那么它们在语义上应该是相同的.

Semantically, they will be different only if the class_variable_dict variable gets shadowed somewhere -- in particular, if (a) self defines a variable of the same name; or (b) self is an instance of a subclass of ClassName, and that subclass (or one of its bases that's still a subclass of ClassName) defines a variable of the same name. If neither of those is true, then they should be semantically identical.

delnam 有一个优点:有一些因素可能会使两者更快.我坚持认为,除非处于非常非常紧密的循环中,否则差异将是微不足道的.为了测试它,我创建了我能想到的最紧密的循环,并用timeit对其计时.结果如下:

delnam has a good point: there are factors that might make either faster. I stand by my assertion that the difference will be trivial unless it's in a very very tight loop. To test it, I created the tightest loop I could think of, and timed it with timeit. Here are the results:

  • 通过var类进行访问: 20.226秒
  • 通过inst var访问: 23.121秒
  • access via class var: 20.226 seconds
  • access via inst var: 23.121 seconds

基于多次运行,误差条看起来大约为1秒-即,这是统计上的显着差异,但可能不值得担心.这是我的测试代码:

Based on several runs, it looks like the error bars are about 1sec -- i.e., this is a statistically significant difference, but probably not worth worrying about. Here's my test code:

import timeit

setup='''
class A:
    var = {}
    def f1(self):
        x = A.var
    def f2(self):
        x = self.var

a = A()
'''
print 'access via class var: %.3f' % timeit.timeit('a.f1()', setup=setup, number=100000000)
print 'access via inst var: %.3f' % timeit.timeit('a.f2()', setup=setup, number=100000000)

这篇关于在Python中访问类变量的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆