Does nesting affect efficiency?
Consider languages like Python or JavaScript that allow functions to be nested like this:
print(vector(a * b),(a * c),(b * c)))
or flat like this:
i = (a * b)
j = (a * c)
k = (b * c)
V = vector(i,j,k)
print(V)
How much does the differ开发者_StackOverflowent format affect performance? Can valid generalizations be made, or does it vary a lot by language?
I expect that an optimizing compiler would do inlining and output approximately the same machine code for both. So perhaps this would be just an issue for interpreted languages?
Any function call adds a small number of machine instructions, including more for more parameters, compared to the same code being present inline, or the compile treating the function as inline.
However, it is a VERY small number of machine instructions. So, in most cases you can easily make that back by for any non-trivial sized input by choosing and implementing a more efficient algorithm.
If you are really on the BLAZING EDGE of performance, (chances are you are not, unless you're working on device drivers) then you can start inlining functions or switching to assembly.
But in any case, write the clearest code possible first, then measure before you start worrying about performance. By doing so you'll have fewer bugs and thus more time to optimize your correctly working code.
Edit: if you're referring to such things as anonymous functions, they cause a performance hit, but, as always, measure first, optimize second.
In the Pascal implementations I've seen, where a nested function is allowed access variables in the outer function's scope, the compiler has to maintain an extra frame pointer for each level of nesting, and dereference it any time the nested function accesses something from the outer scope. The only time I would expect this would be an issue would be if a nested function used an outer function's variable within a tight loop. In that case, performance might be impaired by the extra dereferencing operation; copying the variable to the inner scope outside the loop would avoid that extra overhead.
精彩评论