Is there an overhead when nesting functions in Python?

前端 未结 6 1812
终归单人心
终归单人心 2020-12-04 23:28

In Python, if I have a child function within a parent function, is the child function \"initialised\" (created) every time the parent function is called? Is there any overhe

6条回答
  •  孤城傲影
    2020-12-05 00:17

    There is an impact, but in most situations it is so small that you shouldn't worry about it - most non-trivial applications probably already have performance bottlenecks whose impacts are several orders of magnitude larger than this one. Worry instead about the readability and reusability of the code.

    Here some code that compares the performance of redefining a function each time through a loop to reusing a predefined function instead.

    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)]
    

    When I run this in Python 2.7 on my Macbook Air running OS X Lion I get:

    ** Test "FunctionDefinedEachTime" took 0:00:01.138531 **
    ** Test "FunctionDefinedOnce" took 0:00:00.270347 **
    

提交回复
热议问题