• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cost of type casting...

 
Schuyler Goting
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the efficiency cost of casting a double to an int?
Let's say we are using a double value, but in one particular loop, we have to cast it to an int. And the loop goes through about a thousand times.
Should I declare a seperate int outside of the loop, assign it to the casted value of the double, then use that new int? Would it make a difference? Does Java's compiler notice things like that and do it for me?
Thanks for any help.
--Sky.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the efficiency cost of casting a double to an int?
Generally, small but nonzero. Usually it's unnoticable, but if you loop with a lot of repetitions and there's not much other work being done in the loop, it might be noticeable.
Let's say we are using a double value, but in one particular loop, we have to cast it to an int. And the loop goes through about a thousand times.
Offhand, a thousand (int) casts sounds pretty trivial. I wouldn't worry about this sort of thing until after you've measured total performance and observed that there's actually a problem.
Should I declare a seperate int outside of the loop, assign it to the casted value of the double, then use that new int? Would it make a difference? Does Java's compiler notice things like that and do it for me?
It might; depends on the situation. Or perhaps the compiler won't, but the JIT will optimize it later if it notices that piece of code is slow. Optimization may be more likely if the double was declared as final.
Personally I probably would perform the cast outside the loop, once I noticed it. (Assuming the double value does not change inside the loop.) But really, it's unlikely to matter much, most of the time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!