简体   繁体   English

嵌套会影响效率吗?

[英]Does nesting affect efficiency?

Consider languages like Python or JavaScript that allow functions to be nested like this: 考虑像Python或JavaScript这样的语言允许函数嵌套如下:

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 different 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. 如果你真的在BLAZING EDGE的性能上,(很可能你没有,除非你正在研究设备驱动程序),那么你可以开始内联函数或切换到汇编。

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. 在我看到的Pascal实现中,允许嵌套函数访问外部函数范围内的变量,编译器必须为每个嵌套级别维护一个额外的帧指针,并在嵌套函数访问嵌套函数的任何时候取消引用它。外部范围。 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. 将变量复制到循环外部的内部作用域将避免额外的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM