I always believed that accessing instanced fields from the instanced method/function should give some performance increase as the data should be "more locally available" (I know this is probably dependent on the system and JVM) as opposed to accessing members from a static context. See the code that illustrates my point:
public class Lecture
{
public static void main(String[] args)
{
hold h1 = new hold();
long start1 = System.currentTimeMillis();
h1.accessOOPs();
long end1 = System.currentTimeMillis();
System.out.println("OOPS: "+ (end1 - start1));
hold h2 = new hold();
long start2 = System.currentTimeMillis();
hold.accessStatic(h2);
long end2 = System.currentTimeMillis();
System.out.println("Static (same class): "+ (end2 - start2));
hold h3 = new hold();
long start3 = System.currentTimeMillis();
accessStatic(h3);
long end3 = System.currentTimeMillis();
System.out.println("Static (different class): "+ (end3 - start3));
}
public static void accessStatic(hold h)
{
for (int i=0;i<h.vars.length;i++)
h.vars[i] = i;
for (int i : h.vars)
h.var1 += i;
for (int i: h.vars)
h.name += i;
}
}
class hold
{
int var1;
int vars[] = new int[10000];
String name;
public void accessOOPs()
{
for (int i=0;i<vars.length;i++)
vars[i] = i;
for (int i : vars)
var1 += i;
for (int i: vars)
name += i;
}
public static void accessStatic(hold h)
{
for (int i=0;i<h.vars.length;i++)
h.vars[i] = i;
for (int i : h.vars)
h.var1 += i;
for (int i: h.vars)
h.name += i;
}
}
In the code I have 3 timed examples where I access/modify attributes in a simple object. The first example calls an instance method in the object so theoretically all the attributes should be faster to access since they are in the same context as the method. The second one calls a static function in the object class and uses the dot operator to access the attributes each time. My assumption was that this would be slower. The third example repeats the same operation as the second one but this time does it within a separate class. I was much confused about the timings I received:
Example run 1:
- OOPS: 135
- Static (same class): 130
- Static (different class): 120
Example run 2:
- OOPS: 137
- Procedural (same class): 135
- Procedural (different class): 128
Consistently the OOPs method beat the Static method when the method was in the separate class but I don't understand why that when the static method was in the same class it would beat the instance method. It was only be a slight margin but it was very consistent. Is this only occurring because the static implementation is caching the reference to the object being accessed? If that was occurring then I would think it wouldn't matter that the static method was in a separate class or not, so I am completely confused. Can anyone answer why the static method are not significantly slower?