Performance hit for using TimeUnit conversion in Java

465 Views Asked by At

I was wondering if there is any performance hit (even if it is minimal) to using TimeUnit conversion. e.g. TimeUnit.MINUTES.toMillis(5) vs 300000

If this is a method that will be called frequently and it has to run the toMillis every time is there any performance hit by it? Or perhaps compiler already sets the converted value once and it is never referred to again?

1

There are 1 best solutions below

0
Paul On

Here is the source code for TimeUnit (JDK 10): http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/tip/src/java.base/share/classes/java/util/concurrent/TimeUnit.java

I cannot say what the compiler will do but you may be better off calculating the value yourself, or you may be better off calculating and caching the value, or you may be better off creating a lookup table ahead of time. As @Turing85 astutely pointed out in a comment on your question, "It is hard to say what the JIT will or won't do. Or may only sometimes do."

Rather than ask about toMillis in isolation you'd probably get more benefit from the answers if you posted some sample code to give context to your question. There may be a better way to approach the overall problem so then you wouldn't have to worry about such a small detail as performance when converting minutes to milliseconds.