Partial inlining

I’m just thinking out load here but if someone has an authoritive answer that’d rock too.

It’s not too uncomon to see code for lazy initilization that at the start of a common public method you test a boolean and possibly initilize the rest of an object. eg:

class Foo {
 boolean initilized = false;
 publc void doSomething() {
  if (!initilized) doInit();
  // Other work
 }

 private void doInit() {
  // Some stuff
  initilized = true;
 }
}

threading issues and correctness aside, the above code is a little error prone because as I add new methods I have to remeber to include that whole if statement and method call.

Slightly more robust is the code below:

class Foo {
 boolean initilized = false;
 publc void doSomething() {
  doInit();
  // Other work
 }

 private void doInit() {
  if (initilized) return;
  // Some stuff
  initilized = true;
 }
}

In this case the “if (initilized)” is in the doInit() method and I don’t have to worry about when it is called. But now every time I call doSomething() I incur the overhead of calling doInit() even if it immeaditly returns.

Is it possible for HotSpot to optimize the “if (initilized)” to just before the method call? Is it worth the time and effort?

If this is just a normal object, is there any reason why you wouldn’t want to initialize it in the constructor?

[quote]If this is just a normal object, is there any reason why you wouldn’t want to initialize it in the constructor?
[/quote]
its not that kind of init.

Is it possible for HotSpot to optimize the “if (initilized)” to just before the method call? Is it worth the time and effort?

What you’re describing is runtime constant analysis (very similar to monomorphic analysis), where HotSpot determines that the initialized flag is basically a constant false at runtime and rewrites the method in terms of a false flag. Then, given that the method becomes empty with a false flag, it is a trivial optimization to “inline” that into the calling method.

I wouldn’t be surprised if HotSpot server did this (because it does optimizations of that nature), but I wouldn’t be surprised if it didn’t (because it likely won’t waste the cpu cycles trying to optimize a method that is such a trivial portion of the execution time of your program). You might be able to force it to do this by turning the compilation parameters all the way up. If your init method is small enough, HotSpot may just decide to inline the whole entire thing.

In any case, I wouldn’t be worried about it. I’d bet dimes to dollars that you’ve got much more important things to be concerned about compared to the cost of a non-virtual method call. If HotSpot saves you those nanoseconds, then good for it, otherwise, no big loss.

God bless,
-Toby Reyelts