In java there often objects that serve only to wrap a function and don’t have any state of their own. Example:
class Foo {
void foo () {
System.out.println("foo");
}
static public void main(String[] arg) {
Foo foo = new Foo();
foo.foo();
}
}
I’d like to know if the expression new Foo() is optimized to what in C++ would be an assignment of function pointer. It seems like an obvious thing to do, but when I think about it, the compiler would have to check that foo is not used for synchronization (and possibly something else?). Does the standard say anything about this?
The standard (the VM spec and the JLS that is) doesn’t say anything about this, it’s entirely up to the VM implementations to deal with optimisations.
All the standards specify is a set of invariants that need to be observed. If the VM guarantees that what you do will look like creating an object, then calling a method, then disposing of it, it can do what it wants.
Although the exact manner of optimisation can vary, it is extremely rare that things on this low level are a bottleneck. But as optimisations are done runtime, you can be reasonably certain that they will only be performed if your code is invoked a lot; code that is infrequently used is interpreted rather than compiled into machine code. (But even this may change from VM to VM and may depend on specific command line options.) In your case what would probably happen is that after a lot of runs the VM inlines the method completely, getting rid of both the object creation and the method invocation.
The one thing you can definitely do to “optimise” your code is to declare
Foo(andfoo()) final.