Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 在类中,代码的速度或样式/紧凑性会更好吗?_Performance_Python 3.x_Class_Optimization - Fatal编程技术网

Performance 在类中,代码的速度或样式/紧凑性会更好吗?

Performance 在类中,代码的速度或样式/紧凑性会更好吗?,performance,python-3.x,class,optimization,Performance,Python 3.x,Class,Optimization,我知道答案会因情况和守则的目的而有所不同。我在模块中编写一个类,并意识到重新定义该类的运算符方法需要大量代码。我们对类本身使用继承,为什么不使用方法呢?当然,它确实会让代码慢一点,但它会使代码更加简洁 以以下课程为例: class Ex1: def __init__(self, v): self.v = v def __add__(self, other): # Many lines of essential code return

我知道答案会因情况和守则的目的而有所不同。我在模块中编写一个类,并意识到重新定义该类的运算符方法需要大量代码。我们对类本身使用继承,为什么不使用方法呢?当然,它确实会让代码慢一点,但它会使代码更加简洁

以以下课程为例:

class Ex1:
    def __init__(self, v):
        self.v = v
    def __add__(self, other):
        # Many lines of essential code
        return self.v + other.v
    def __sub__(self, other):
        # Many lines of essential code
        return self.v - other.v
    def __mul__(self, other):
        # Many lines of essential code
        return self.v * other.v
    def __truediv__(self, other):
        # Many lines of essential code
        return self.v / other.v
以及:

使用timeit模块对其进行测试,我得到以下结果:

>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2401711247332514
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2278626568422624
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2270929157546107
>>>
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6781722774976515
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6906975044787487
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.678191572340893
所以
Ex2
大约比
Ex1
慢1.36倍。但在某些(罕见的)情况下,如果使用
Ex2
的“变通方法”,则可以消除数百行代码。但总的来说,速度比消除线路更重要吗?专业人士是否愿意牺牲一点速度来消除多余的代码行

编辑:


我意识到我可以通过将
op
参数(来自符号;例如“+”)替换为实际函数(例如ops.add)来消除if语句。

我看不出你是如何消除那里的行的。如果你有多余的行,把它们放在一个方法中,然后调用这个方法,而不是非多余的东西,但是不要在一个调用中聚合好的分离调用,只是为了再次分离它。
#如果elif语句比字典快
你做过任何测试来证明这一点吗?我真的很怀疑这种说法。而且,我自己做的测试也显示了相反的结果,你是对的。我道歉。在我的初始测试中,我在init中而不是在init之前创建字典。每次创建字典的速度都比if语句慢。@ClaytonGeist看不到这个答案及其指向的链接:Python中的字典查找时间平均为O(1)(甚至超过)。
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2401711247332514
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2278626568422624
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2270929157546107
>>>
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6781722774976515
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6906975044787487
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.678191572340893