Demeter's law (suggestion) and tell don't ask - Part 3 of 3

Part two showed an example of how to get objects to tell-not-ask and suggested that the resultant dumb forwarding methods may soon acquire useful behaviour thereby becoming not-so-dumb-anymore.

In this post, I'd like to touch upon perceived performance overheads. The pragmatic programmer (section 26) has this to say about wrapper (forwarding) methods introduced to break method chains:
These wrapper methods will impose both a runtime cost and a space overhead...
Note that the number of method calls is the same whether one uses forwarding or not. To use the example in the book:

aSelection.getRecorder().getLocation().getTimeZone(); //3 method calls

when wrapped gives...

aSelection.getTimeZone(); // still 3 calls.
  1. aSelection.getTimeZone
  2. recorder.getTimeZone() in Selection and
  3. location.getTimeZone() in Recorder
The space overhead comes about because of the definition of new forwarding methods. The increased class footprint might result in extra runtime cost of classloading and also some minor impact on memory addressing and cache misses because the class file's memory footprint is slightly larger than before. (thanks to Josh for the explanation)

Extensive use of forwarding methods may also have a noticeable effect on stack usage patterns in multithreaded environments (like a web server). Without forwarding, the stack goes wind-unwind-wind-unwind-wind-unwind as each method returns before you make the next call. With forwarding, the stack goes wind-wind-wind-unwind-unwind-unwind. This may push up the peak memory usage per thread.

However, for all practical purposes all of the above effects are minor compared to the not-so-minor gains in encapsulation.

2 comments:

Robin Clowers said...

I think it is important to realize that method calls are also inlined by modern compilers quite a bit. In practice, you don't really need to worry about the overhead of method calls.

Sriram said...

@Robin

Polymorphic calls cannot be inlined. For all practical purposes though, I agree that one needn't worry about the overhead of method calls.

Post a Comment