Java Performance Tuning

Java(TM) - see bottom of page

|home |services |training |newsletter |tuning tips |tool reports |articles |resources |about us |site map |contact us |
Tools: | GC log analysers| Multi-tenancy tools| Books| SizeOf| Thread analysers| Heap dump analysers|

Our valued sponsors who help make this site possible
JProfiler: Get rid of your performance problems and memory leaks! 

Training online: Concurrency, Threading, GC, Advanced Java and more ... 

The Commando Pattern

JProfiler
Get rid of your performance problems and memory leaks!

Modern Garbage Collection Tuning
Shows tuning flow chart for GC tuning


Java Performance Training Courses
COURSES AVAILABLE NOW. We can provide training courses to handle all your Java performance needs

Java Performance Tuning, 2nd ed
The classic and most comprehensive book on tuning Java

Java Performance Tuning Newsletter
Your source of Java performance news. Subscribe now!
Enter email:


Training online
Threading Essentials course


JProfiler
Get rid of your performance problems and memory leaks!


The Commando Pattern provides specialized access to methods and variables to enable optimal performance in critical and non-critical sections of code. The Commando Pattern enables optimal performance in any application, and is a pattern that is frequently applied in projects. Although the Commando Pattern does have some maintenance tradeoffs, these are usually considered acceptable in pre-production phases of a project. The Commando Pattern provides both high performance application execution, and rapid development progress, and is even a pattern well suited to introductory levels of programmer expertise.

An example of using the Commando Pattern is perhaps the best way to appreciate its strengths. The Commando Pattern is applicable in many areas of programming, but here I'll use the example of iterating through an ArrayList. For clarity, I'll iterate through a list of strings, searching each element (i.e. each string) for a particular substring. A simple example follows:


      int count = 0;
      for(int i = 0; i < arraylist.size(); i++)
      {
        if (((String) arraylist.get(i)).indexOf("xy") != -1 )
          count++;
      }

This example shows a straightforward loop, accessing each element in the list, casting the element into a String object so that the indexOf method can be used to detect whether the substring "xy" is present in any element. In the case of our example here, we simply increment a count variable if the test is true, i.e. we are counting how many strings in the list contain the substring "xy".

Applying The Pattern

Now let's apply the Commando Pattern to this code. It is common knowledge that accessing variables through a method call is less efficient than accessing the variable directly. So the Commando Pattern tells us here to provide a specialized high performance access to the elements, bypassing the method access. This is easily achieved here: simply access the data field holding the array.

Ideally, this would be a simple access, and the code would look like


    Object[] elementData = arraylist.elementData;
    int elementSize = arraylist.size();
    int count = 0;
    for(int i = 0; i < elementSize; i++)
    {
      if (((String) elementData[i]).indexOf("xy") != -1 )
        count++;
    }

Note that we need to use the array size because the size of the ArrayList.elementData field can be larger than the size of the array for efficient growing of arrays, i.e. there can be unused capacity in the ArrayList.elementData array.

Bypassing Access Control

That looked easy enough, but unfortunately, the ArrayList.elementData field is declared as a private field in the ArrayList class, so this code would not compile. But Java gives us more than one way to access a variable. Using reflection we can access that same variable in a different way:


    Field elementDataField = ArrayList.class.getDeclaredField("elementData");
    Object[] elementData = (Object[]) elementDataField.get(arraylist);

Actually, this doesn't seem to get us any closer, since although the code would now compile, there is instead a runtime access exception when the execution reaches this access point. But there was a reason to do it this way, because Java reflection actually let's us bypass that access control fairly easily by setting the field to be accessible


    elementDataField.setAccessible(true);

So let's combine those changes, and we end up with the following code which: accesses the underlying element array of the ArrayList object, bypassing the access security; get's the size of the ArrayList object; then iterates through the underlying array directly, bypassing the ArrayList.get() method call.


    Field elementDataField = ArrayList.class.getDeclaredField("elementData");
    elementDataField.setAccessible(true);
    Object[] elementData = (Object[]) elementDataField.get(arraylist);
    int elementSize = arraylist.size();
    int count = 0;
    for(int i = 0; i < elementSize; i++)
    {
      if (((String) elementData[i]).indexOf("xy") != -1 )
        count++;
    }

Speedups

The end result of applying the Commando Pattern to this problem gives us a speedup for any iterations on significant sized lists, even after including the extra cost of accessing the field through reflections. Testing with a large array using the 1.4.2 JVM gave a speedup of 20%! (Full code listing for example test)

The Commando Pattern was originally proposed by Michael Duell in his excellent article covering "Resign Patterns", and it is certainly worth quoting from that paper his definition of the Commando Pattern

The Commando Pattern is used to get in and out quick, and get the job done. This pattern can break any encapsulation to accomplish its mission. It takes no prisoners.

The Commando Pattern and other similarly useful patterns can make your implementation stand out from the crowd. If you don't know about this pattern and its effects, you cannot consider yourself "the compleat programmmer".

This article on the Commando Pattern was first published on April 1st, 2004
Author: Jack Shirazi

In case you haven't yet identified this as a joke, it is an April fool. The code all works exactly as advertised, but this pattern of programming is definitely not a good practice, and so does not earn the right to be called a "pattern". The quoted Michael Duell article is a list of joke patterns, of which the Commando pattern is one.


Last Updated: 2025-01-27
Copyright © 2000-2025 Fasterj.com. All Rights Reserved.
All trademarks and registered trademarks appearing on JavaPerformanceTuning.com are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. JavaPerformanceTuning.com is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
URL: http://www.JavaPerformanceTuning.com/articles/commando.shtml
RSS Feed: http://www.JavaPerformanceTuning.com/newsletters.rss
Trouble with this page? Please contact us