Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost for casting primitive types in Java

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.

like image 445
mat_boy Avatar asked Jun 26 '13 08:06

mat_boy


1 Answers

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.

like image 68
omer schleifer Avatar answered Sep 30 '22 10:09

omer schleifer