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 overhead associated with nesting a function within another?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The code object is pre-compiled so that part has no overhead. The function object gets built on every invocation -- it binds the function name to the code object, records default variables, etc.
Executive summary: It's not free.
I was curious about this too, so I decided to figure out how much overhead this incurred. TL;DR, the answer is not much.
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:
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.
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.
When I run this in Python 2.7 on my Macbook Air running OS X Lion I get:
Yes, a new object would be created each time. It's likely not an issue unless you have it in a tight loop. Profiling will tell you if it's a problem.
The other answers are great and really answer the question well. I wanted to add that most inner functions can be avoided in python using for loops, generating functions, etc.
Consider the following Example:
This example is a little goofy, but I hope you can see my point nonetheless. Inner functions are often not needed.