Potential optimization in VM
Sorry if this has already been suggested, or is old hat... but consider the following:
class A
{
public void method();
}
class B extends A
{
public void method();
}
class Test
{
private A local;
public Test(A a)
{
local = a;
}
public void method()
{
local.method();
}
}
Now the question is does the method in the Test class have to call the V-Table on local to find out whether A.method() or b.method() is being called? My point is that we know when the Test class is created exactly what instantiated object 'local' will be set to. We also know local will not change since it is private and there is no code to change it outside of the constructor. Taking this into account we could optimize away the V-Table access in a lot of instances and call methods directly and safely. What are peoples thoughts?
- Login to post comments
final
I don't think you can rule out the possibility of local being changed by a subclass of Test. I think it would be necessary to at least declare local as "private final A local;".
BTW, the new Java Memory Model JSR has a list of optimisations (with proofs) that can be done.
Not quite...
From the above code it is absolutely impossible to tell what will be invoked, method() from class A or method() from class B when local.method() is executed. It is so because it depends on the object that you pass to the Test constructor. This object can be an instance of class A or an instance of class B.
Clarification
Perhaps I should clarify, When the test class is instantiated the object passed to the Test constructor is known. The code for the Test class can be fixed up to point directly to A.method() or B.method() depending on the value passed to the constructor.