Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda