+1

Replace Temp with Query might add performance overhead

Hoang Tran il y a 8 mois mis à jour par vaclav hapla il y a 3 mois 3

Image 1691

I believe the first solution on the left is more efficient than the second as it caches the result of basePrice for reference in conditional expressions. Can you please explain why we should favour the second one ?

Yeah, I agree. The solution needs to calculate the base price three times. I also miss the `quantity` and `itemPrice` initialization.

The cost of the operation for this one is small, though. The performance impact won't be big, because the calulcation is very trivial. It can be fixed by creating a class that caches the value. That's what I would do in this case. The object would get the `quantity` and `itemPrice` as associations and have a method to calculate the price. That will increase the lines of code, but gives more reusability and no performance loss.

  1. This is a very trivial calculation.
  2. It is written 3x but executed 2x since it's in the if-else.

The overhead is most likely negligible.

In general, you shouldn't start from the assumption that it has any noticeable overhead and complicate your code or not do the refactoring based on that assumption (which is most often false). Only if profiling reveals that it might pay off. Furthermore, e.g. in the case of C++, the compiler might inline it automatically anyway.

And it's discussed in the Good To Know / Performance section in https://refactoring.guru/replace-temp-with-query.