Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Does this function swapping pattern have a name?

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!