0

I'm trying to know how to calculate what is the real impact of changes like the following:

    if ((payload.transactions?.length > 0) &&
        (user.Type === UserType.Premium && user.status === UserStatus.Active)
    ) {
        doSomeStuf();
    }
    const hasTransactions = () => payload.transactions?.length > 0;
    const isActivePremium = () => { 
        return user.Type === UserType.Premium && user.status === UserStatus.Active; 
    }
    
    if (hasTransactions() && isActivePremium()) {
        doSomeStuf()
    }

where conditions are moved from an if statement to a function in order to improve the code readability

El Facha
  • 113
  • 4
  • 3
    Unless you need to do those things millions of times per minute it will make no difference at all. – Pointy May 15 '23 at 15:49
  • Function calling has significant overhead compared to just executing the code directly. As @Pointy said, the impact will depend on how many times you call the code. – Barmar May 15 '23 at 15:52
  • You could break the condition up without making them into functions, `const hasTransactions = payload.transactions?.length > 0; `, and then `if (hasTransactions &&...` The function wrapping isn't adding anything here. – Keith May 15 '23 at 15:57
  • Use `performance.now()` to measure the difference in execution time – Artur Minin May 15 '23 at 16:02
  • @Keith The function wrapping *does* help: `isActivePremium()` is not evaluated if `hasTransactions()` returns false. If you create two boolean variables, both expressions have to be evaluated all the time. – Bergi May 15 '23 at 16:03
  • @Bergi Yes, I understand short circuit boolean evaluation, but I'd be surprised if the nano seconds saved there would be more than a function expression, but I might be wrong. – Keith May 15 '23 at 16:08

0 Answers0