擅长:python、mysql、java
<p>这是一个影响,但在大多数情况下,它是如此之小,你不必担心它-大多数非平凡的应用程序可能已经有性能瓶颈,其影响比这个大几个数量级。而是担心代码的可读性和可重用性。</p>
<p>这里有些代码比较了每次通过循环重新定义函数与重用预定义函数的性能。</p>
<pre><code>import gc
from datetime import datetime
class StopWatch:
def __init__(self, name):
self.name = name
def __enter__(self):
gc.collect()
self.start = datetime.now()
def __exit__(self, type, value, traceback):
elapsed = datetime.now()-self.start
print '** Test "%s" took %s **' % (self.name, elapsed)
def foo():
def bar():
pass
return bar
def bar2():
pass
def foo2():
return bar2
num_iterations = 1000000
with StopWatch('FunctionDefinedEachTime') as sw:
result_foo = [foo() for i in range(num_iterations)]
with StopWatch('FunctionDefinedOnce') as sw:
result_foo2 = [foo2() for i in range(num_iterations)]
</code></pre>
<p>当我在运行OS X Lion的Macbook Air上运行Python2.7时,我得到:</p>
<pre><code>** Test "FunctionDefinedEachTime" took 0:00:01.138531 **
** Test "FunctionDefinedOnce" took 0:00:00.270347 **
</code></pre>