optimization - 保存计算值而不是多次重新计算的术语是什么?

标签 optimization terminology temporary-objects

当您有这样的代码时(用 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/

相关文章:

计算插入排序中的交换次数

python - 如何找到将 N 个观察值分配到 M 个组的最佳方法?

c++ - 用于简单数组创建和 i/o 的 C vs C++ 代码优化

javascript - “non-AJAX”请求的正确术语是什么?

c++ - 什么时候临时用作命名对象的初始值设定项被销毁?

java - 如何在不创建临时对象的情况下迭代嵌套的 TreeMap

数学编程优化

process - 帮我定义流程和程序?

polymorphism - "polymorphism"一词从何而来?

c++ - 构建 vector 时如何去除(一个)不必要的拷贝?