I had a function that needs to check 2 conditions before doing something. This function gets run a lot so, even though the first condition is not particularly slow to check (and is the faster of the 2) it still adds up to a not insignificant amount of time.
function checkBothConditions() {
if (condition1){
if (condition2) {
// do stuff
}
}
}
In my specific case, once condition1 becomes true once, it will remain true at least until condition2 also becomes true.
Thus I realised that I can eliminate the first test for a period of time by replacing the function.
let checkBothConditions;
const onlyCheckCondition1 = function() {
if (condition1) {
checkBothConditions = onlyCheckCondition2; //skip condition1 check next time
onlyCheckCondition2(); // run the 2nd test right away
}
}
const onlyCheckCondition2 = function() {
if (condition2) {
// do stuff
checkBothConditions = onlyCheckCondition1; // reinstate check for condition1. since it may no longer be true.
}
}
checkBothConditions = onlyCheckCondition1;
This code is significantly faster in my specific case (although I wouldn't expect it to be faster in the general case!)
Is there a name for this pattern of swapping functions around for performance reasons?