fentalyn
fentalyn

Reputation: 79

Which is more efficient code (parseInt several times or one time and put it in variable)?

I'd like to know if the first or the second way are more efficient and I am also asking about similar situations because they come up pretty often. It's all frontend code (React). I'd really like to know. Thanks!

(input) => {
  setState(parseInt(input, 10))
  updateAuction(parseInt(input, 10))
  ...

Or, saving the result of parseInt into a var and using the var

(input) => {
  const parsedInput = parseInt(input, 10)
  setState(parsedInput)
  updateAuction(parsedInput)
  ...

This and similar situations bother me every day, because I don't know the answer. I also have string comparisons quite often.

logoVariant === "small" && do something
logoVariant === "small" && do something else

or

const isLogoSmall = logoVariant === "small"
isLogoSmall && do something
isLogoSmall && do something else

Thanks!

Upvotes: 0

Views: 45

Answers (1)

John M.
John M.

Reputation: 795

It is always faster to cache the comparison result rather than doing a string comparison twice as the string comparison operation is much more complex than evaluating the cache result. This isn't as clear in languages with an advanced compiler like C++ where the compiler may be able to recognise the redundancy. The balance is making code less easy to read, and potentially increased memory usage if you are caching more complex results (although not in this case).

Upvotes: 3

Related Questions