Is there an overhead when nesting functions in Python?

前端 未结 6 1809
终归单人心
终归单人心 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-04 23:54

    I was curious about this too, so I decided to figure out how much overhead this incurred. TL;DR, the answer is not much.

    Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from timeit import timeit
    >>> def subfunc():
    ...     pass
    ... 
    >>> def no_inner():
    ...     return subfunc()
    ... 
    >>> def with_inner():
    ...     def s():
    ...         pass
    ...     return s()
    ... 
    >>> timeit('[no_inner() for _ in range(1000000)]', setup='from __main__     import no_inner', number=1)
    0.22971350199986773
    >>> timeit('[with_inner() for _ in range(1000000)]', setup='from __main__ import with_inner', number=1)
    0.2847519510000893
    

    My instinct was to look at percents (with_inner is 24% slower), but that number is misleading in this case, since we'll never actually just return the value of an inner function from an outer function, especially with functions that don't actually do anything.
    After making that mistake, I decided to compare it to other common things, to see when this does and does not matter:

        >>> def no_inner():
        ...     a = {}
        ...     return subfunc()
        ... 
        >>> timeit('[no_inner() for _ in range(1000000)]', setup='from __main__ import no_inner', number=1)
        0.3099582109998664
    

    Looking at this, we can see that it takes less time than creating an empty dict (the fast way), so if you're doing anything non-trivial, this probably does not matter at all.

提交回复
热议问题