gpt4 book ai didi

perl - if 语句在循环内部还是外部?

转载 作者:行者123 更新时间:2023-12-03 07:43:48 24 4
gpt4 key购买 nike

如果我这样做会更好吗:

foreach my $item ( @array ) {
if ( $bool ) {
.. code ..
}
else {
.. code ..
}
}

if ( $bool ) {
foreach my $item ( @array ) {
}
}
else {
foreach my $item ( @array ) {
}
}

最佳答案

我会离开premature optimization放在一边。

"Premature optimization is the root of all evil" - Donald Knuth

您应该首先考虑可维护性。考虑到代码的逻辑结构,以更有意义的方式对它们进行分组(例如将相关语句分组在一起)。

如果您稍后确定性能是一个问题,请尝试使用分析器之类的工具进行测量,以了解瓶颈所在。很可能,它不在那里。来自代码完成 2:

Barry Boehm reports that 20 percent of a program's routines consume 80 percent of its execution time. In his classic paper "An Empirical Study of Fortran Programs," Donald Knuth found that less than four percent of a program usually accounts for more than 50 percent of its run time.

在必要之前,我们不应该尝试猜测要优化的地方,因为我们大多数人都不擅长猜测代码中缓慢的部分在哪里。边做边优化的程序员也会花费大约 96% 的时间来优化不需要优化的代码。另一件需要考虑的事情是,代码调优(如本示例中所示)考虑了性能的可读性和可维护性之间的权衡:

Focusing on optimization during initial development detracts from achieving other program objectives. Developers immerse themselves in algorithm analysis and arcane debates that in the end don't contribute much value to the user. Concerns such as correctness, information hiding, and readability become secondary goals, even though performance is easier to improve later than these other concerns are. Post hoc performance work typically affects less than five percent of a program's code. Would you rather go back and do performance work on five percent of the code or readability work on 100 percent?

我并不是说不要优化,而是只有在最后才优化代码,当您拥有大局和工具来指导您时方向正确。

额外:要回答性能本身的问题:

This ["unswitching" the code] is good for about a 20 percent time savings:

Language        Straight Time    Code-Tuned Time    Time Savings
C++ 2.81 2.27 19%
Java 3.97 3.12 21%
Visual Basic 2.78 2.77 <1%
Python 8.14 5.87 28%

A hazard distinct to this case is that the two loops have to be maintained in parallel. [...] you have to remember changing the code in both places, which is an annoyance for you and a maintenance headache for anyone else who has to work with the code.

This example also illustrates a key challenge in code tuning: the effect of any specific code tuning is not predictable. The code tuning produced significant improvements in three of the four languages but not in Visual Basic. To perform this specific optimization in this specific version of Visual Basic would produce less maintainable code without any offsetting gain in performance. The general lesson is that you must measure the effect of each specific optimization to be sure of its effect - no exceptions.

检查this other这里有关于SO的问题。和this来自《Code Complete》第一版。

关于perl - if 语句在循环内部还是外部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2242238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com