Spooky
Spooky

Reputation: 355

How and when a static final field value is calculated?

Is the value of this field calculated every time I access it or is it replaced at start by 1.73... ?

private static final double SQRT_3 = Math.sqrt(3);

I think not but is there any advantage to put the value directly ? I saw that in someone code

Upvotes: 1

Views: 290

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96434

In your posted code, the SQRT_3 field will get initialized at the time that the class is loaded, calling Math.sqrt(3). Later, when you access the field, you get the value that was returned by that first call, and Math.sqrt doesn't get called any more.

The advantage of adding the value directly instead of calculating it with Math.sqrt is that the value will be a constant expression that can be inlined by the compiler. This is a real micro-optimization, though. Measure where the bottlenecks are and fix those, don't sweat the small stuff.

Upvotes: 3

Related Questions