当您有这样的代码时(用 java 编写,但适用于任何类似的语言):
public static void main(String[] args) {
int total = 0;
for (int i = 0; i < 50; i++)
total += i * doStuff(i % 2); // multiplies i times doStuff(remainder of i / 2)
}
public static int doStuff(int i) {
// Lots of complicated calculations
}
你可以看到还有改进的余地。
doStuff(i % 2)
只返回两个不同的值 - 一个用于 doStuff(0)
在偶数和一个为 doStuff(1)
在奇数上。因此,每次说 doStuff(i % 2)
都会浪费大量的计算时间/功率来重新计算这些值。 .你可以这样改进:public static void main(String[] args) {
int total = 0;
boolean[] alreadyCalculated = new boolean[2];
int[] results = new int[2];
for (int i = 0; i < 50; i++) {
if (!alreadyCalculated[i % 2]) {
results[i % 2] = doStuff(i % 2);
alreadyCalculated[i % 2] = true;
}
total += i * results[i % 2];
}
}
现在它访问存储的值而不是每次都重新计算。保持这样的数组似乎很愚蠢,但对于像从
i = 0, i < 500
循环这样的情况你正在检查 i % 32
每次或某事,数组都是一种优雅的方法。这种代码优化有术语吗?我想阅读更多关于不同形式及其约定的内容,但我缺乏简洁的描述。
最佳答案
Is there a term for this kind of code optimization?
就在这里:
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
https://en.wikipedia.org/wiki/Memoization
关于optimization - 保存计算值而不是多次重新计算的术语是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33589526/