所以问题是如何减少计算?
class Example{
constructor(exampleArray){
this.exampleArray = exampleArray;
}
function exampleMethod(){
let i = 0;
for(i = 0; i < this.exampleArray.length; i++){
if(i < par1){ // par1 times same setup
someExampleSetupFunction(); /* already calculated if i > 0 ,
so how to bring it out ?*/
someOperations(); // setup values changed.
}else if(i < par2){ // par2 times same setup
someExampleSetupFunction(); /* already calculated if i > par1,
so how to bring it out ?*/
someOperations2(); // setup values changed
}...
...else if(i < this.exampleArray.length){
someExampleSetupFunction();
someOperationsN(); // setup values changed
}
}
}
}
答案 0 :(得分:0)
像这样,也许?
请注意,我已将someExampleSetupFunction
更改为箭头功能,因为您调用它的方式会导致它丢失this
上下文。
class Example{
constructor(exampleArray){
this.exampleArray = exampleArray;
}
exampleMethod (){
let i = 0;
const operations = [
someOperations,
someOperations2,
someOperations3,
someOperations4
];
const someExampleSetupFunction = () => {
if(this.exampleArray[i] === "param1"){
// do something...
}else if(this.exampleArray[i] === "param2"){
// do something else...
}
}
for(i = 0; i < this.exampleArray.length; i++){
operations.forEach((op) => {
someExampleSetupFunction();
op();
});
}
}
}
答案 1 :(得分:0)
确定。首先,在你的代码中,当你做...
for(i = 0; i < this.exampleArray.length; i++){
someExampleSetupFunction();
someOperations();
someExampleSetupFunction();
someOperations2();
someExampleSetupFunction();
someOperations3();
someExampleSetupFunction();
someOperations4();
}
这称为 RECURSION ,问题在于它会降低性能并降低执行时间。你最好避免这种做法。
避免递归的最佳方法是使用 buttom-up 代码实践,这样可以节省递归在构建调用堆栈时产生的内存成本。
let result = <result>;
for(i = 0; i < this.exampleArray.length; i++){
//Some operations that return a <result>
result += <result>;
}
这里有一个link,了解有关自下而上练习的详细信息