Question

I have an algorithm written in Java that iteratively does primitive casting like:

int val = (int) Math.max(val1, val2);

Since I'm trying to improve the performance of the algorithm, I want to know if repeating the above casting must be avoided, e.g. by using something like:

int val = ((val1>val2) ? val1 : val2);

PS: I did a search into Stackoverflow but I didn't find a similar answer.

Était-ce utile?

La solution

Let's assume for the sake of discussion val1 and val2 are both double and you still want to get an int (since you say this is just an example).

I would suggest first to compare the amount of time it takes you to call

double val = Math.max(val1, val2)

vs:

int val = (int) Math.max(val1, val2);

If you run this benchmark correctly (meaning do wormup in the JVM and measure the amount of time for millions of calls) most likely you will find the amount of time in the cast is neglilibe compared to Math.max()

In general, before making the code less readable and more complicated for the sake of performance, first you need to know that the performance gain is real.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top