0

Possible Duplicate:
Why defining class as final improves JVM performance?

I have the following class in my project:

public final class LinkNode
{
  public int value;
  public LinkNode next;

  public LinkNode(int value, LinkNode next)
  {
    this.value = value;
    this.next = next;
  }

  public LinkNode(int value)
  {
    this(value, null);
  }
}

The slowest line in my code (which is overall quite complex) is where I construct new LinkNodes.

I found that when I made the class final, the code ran significantly faster. Why is that?

Is there anything else I can do in this class to optimize this class, specifically the primary constructor?

(For example, are getters/setters faster than public fields? Are there other modifiers I can add? Etc.)

Community
  • 1
  • 1
dsg
  • 12,924
  • 21
  • 67
  • 111

2 Answers2

1

I found that when I made the class final, the code ran significantly faster. Why is that?

I think it is because there is a flaw in your benchmarking methodology.

Assuming that you are using a recent Hotspot JRE, the JIT compiler is smart enough that the final modifier on a class should have no performance impact ... unless you actually use a subclass of the class in your application.

If you want confirmation, post details of your methodology, including the benchmark code and the benchmark results.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Declaring a class final directly affects the performance of JVM. Final classes and methods can be inlined after being loaded into the JVM, because at that point the JVM knows definitely that the method is final. Therefore there might be a performance improvement on the just-in-time Java compilers.

You may want to check the links provided in here for further detailed information: http://www.javaperformancetuning.com/tips/final.shtml

Korhan Ozturk
  • 11,148
  • 6
  • 36
  • 49
  • The JIT will inline methods anyhow and deoptimize it if necessary. I'm going with Stephen's explanation: flawed test. – Voo Jan 19 '12 at 20:52
  • 1
    I would not rely on the information in the linked page. 1) It says "could" and "would" all over the place, meaning that the author is stating theories rather than facts. 2) There are no references to benchmarks or definitive sources. 3) There are not even mentions of specific versions / releases of Java, and it is a known fact that real performance depends on this. – Stephen C Jan 19 '12 at 23:06