1

I want to define some constants in a class, which is used for time management. My class looks as follows:

public class TimeManager {
    public static final long SECOND = 1000;
    public static final long MINUTE = SECOND * 60;
    public static final long HOUR = MINUTE * 60;
    public static final long DAY = HOUR * 24;
    .
    .
    .
}

Are there any performance problems with these constant definitions? Are the values computed by the Java compiler?

Stefan
  • 136
  • 10
  • 1
    Well there's a problem in that they're non-final... and is there any reason you're not just using `TimeUnit`? – Jon Skeet May 05 '17 at 15:06
  • I'm like 90% sure it does these calculations at compile time. If not, don't forget the JIT optimizer can do many more optimizations with the byte codes, which surely will result in the above being done once only. Basically I'd act like it does and not worry about it. – markspace May 05 '17 at 15:06
  • 2
    Well they're static anyway, so the initialization is only going to happen a single time. I'd still suggest removing them entirely *or* making the final though. – Jon Skeet May 05 '17 at 15:06
  • 9
    Even if it doesn't optimize them - are three multiplications really going to be the performance bottleneck in your application? – Joe Clay May 05 '17 at 15:07
  • I wonder if we should roll back OPs edit, because his manipulation of the original question renders "Brij Patel" answer useless ("wont be calculated by the compiler"), which isn't allowed ... – Tom May 05 '17 at 15:15
  • @Tom I thinks the OP just clarified what he actually wanted to know. That Brij's answer (which in my opinion is low quality) doesn't fit any more is unfortunate. A rollback wouldn't improve the question but it could render the better quality answer by Thomas useless. – kapex May 05 '17 at 15:29
  • 1
    See also the accepted answer to [this question](http://stackoverflow.com/questions/32034709/), which cites relevant sections of the JLS. Note that there are multiple Java compilers. Note that a specification that says "can be" is not the same as "will always be" -- though the latter may certainly be true in practice. – Andy Thomas May 05 '17 at 15:30
  • @Kapep If OP fails to ask what he really want to know and already got an answer for the original question, then (s)he is supposed to ask a new question. Btw: both answers are of low quality and Thomas failed to do what he is supposed to do (with his reputation and experience): vote to close as dupe. – Tom May 05 '17 at 15:40

1 Answers1

7

Yes, it does:

$ javap -constants TimeManager
Compiled from "TimeManager.java"
public class TimeManager {
  public static final long SECOND = 1000l;
  public static final long MINUTE = 60000l;
  public static final long HOUR = 3600000l;
  public static final long DAY = 86400000l;
  public TimeManager();
}

As commenters have pointed out, it doesn't really matter though.

Thomas
  • 174,939
  • 50
  • 355
  • 478