Performance Tips: Java without a JITVariablesVariable accessIn terms of the source code, variables in Java reside in two principle places. They can
belong to an object ("instance variables") or class (static variables or "class variables"),
in which case their declration sits outside of the method definitions.
Or they can be "local variables" declared inside a method. So in the following example,
variable public class Obj { private byte[] byteData = new byte[10]; public void doCalculation() { int total = 0; for (int i = 0; i < 10; i++) { total += byteData[i]; } } } Other than the place in which they are declared, the syntax for declaring and accessing these types of variables is very similar. What happens under the hood is quite different. Local variables such as Instance variables such as A potential performance hit of the code above, then, is that it uses the relatively expensive
public class Obj { private byte[] byteData = new byte[10]; public void doCalculation() { int total = 0; byte[] byteData = this.byteData; for (int i = 0; i < 10; i++) { total += byteData[i]; } } } In this version, the VM 'finds' the Look out for this technique in various places in the JDK source code. Variable initialisationIt's common to see code like this: public class Counter { private int value = 0; //... } This makes it nice and clear that the variable public class Counter { private int value; //... } Conversely, if you are
public class Counter { private int value; public Counter() { super(); value = 0; } } Similarly, if you write: public class Obj { private int[] data = {1, 2, 3}; } this is again just a shorthand and will be turned into something like this by the compiler: public class Obj { private int[] data; public Obj() { super(); data = new int[3]; data[0] = 1; data[1] = 2; data[2] = 3; } } In other words, there isn't a performance gain from declaring variable values at the top of the class: it's just a lexical shorthand. This is different from C programming on some platforms, where an initial value of a global variable can be embedded in a program's object file. All editorial content copyright (c) Neil Coffey 2007. All rights reserved. |