1

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?

Kirit
  • 389
  • 2
  • 3
  • 11
  • 4
    Do not try to optimize if you have no indications that there is a problem. It is hard to say what the JIT will or won't do. Or may only sometimes do. – Turing85 May 11 '18 at 19:19
  • Yes, there is a performance hit, at least until JIT is invoked, at which point the performance hit may be eliminated, or reduced. The hit is small (method call + 4 `if` statements), so it is unlikely to be significant enough to matter, but only testing can verify that for sure. Until testing shows that `toMillis(5)` is an issue, keep using it, because it describes the intended conversion much better than `5 * 60 * 1000` or `5 * 60000` or `300000`. Beware [premature optimization](https://softwareengineering.stackexchange.com/q/80084/202153). – Andreas May 11 '18 at 19:30
  • 2
    If you're that worried about it you can make a constant using timeunit and only pay the cost of calculation once. – Hitobat May 11 '18 at 19:49

1 Answers1

0

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.

Paul
  • 19,704
  • 14
  • 78
  • 96