要问这个问题来解释我的真实问题非常困难,但我在这里尝试一下。我有一个函数,里面是一些变量,函数内部是另一个函数,它是一个永远在变化的函数。这看起来可能很复杂,但让我在这段代码中解释一下:
var a, b, x;
function myF(y, fn) {
x = y;
a = x * 2;
b = x * 3;
//in my real code a and b are much complicated, and there are 10 variables,
//and almost all of them are always changing (depending on scroll)
//i need them to be defined, but i don't always use them
//how which is used depends on the fn.
return fn();
}
function innerOne() {
return a * x;
}
function innerTwo() {
return b * x;
}
myF(3, innerOne);
//when this function called, the b is also calculated, but never used
myF(6, innerTwo);
//same situation, but with a
我希望通过不计算实际不需要的变量来提高代码的性能,所以我想知道是否有办法检查fn()
使用的元素,并只计算它们。 / p>
我的原始代码看起来像this
答案 0 :(得分:2)
我想知道是否有办法检查fn()使用的元素,并计算这些元素。
没有。在您运行该函数之前,您无法确定函数将访问哪些变量,这是halting problem的特化。
您可以通过(例如)使用函数上的toString
来检索其源代码并执行静态分析,但即使这样,您也无法确定它将有条件地访问哪些变量而不实际执行代码。
这在JavaScript或大多数其他语言中确实不是问题。这里的简单解决方案是重新考虑您是否已经构建了代码,以便按需完成计算,而不是预先计算它们。