5 Easy Java Optimization Tips

January 24th, 2012 Leave a comment 10 comments
Like the article?
Java Optimization Tips

When writing Java code it can be easy to make simple mistakes that seem harmless on the surface but, as our applications grow larger, they can show themselves to be slow, resource intensive processes that could use a tune-up. Luckily there are some easy ways to optimize your Java code that you can begin using today. Here, we will introduce you to five of them.

1. Avoid unnecessary casting

Casting, for the new developer, is a way of converting between reference data types. Most casting is done to allow a more generic form of programming where your code will be able to work with all types of objects and classes that are descended from some type of base class.

However, new programmers do not always write these casting statements correctly and are creating a situation where they are improperly casting and creating more overhead for their application in the VM than necessary. An example:

class MyCastingClass {
	public Object myMethod() {
		String myString = "Some data";
		Object myObj = (Object) myString;
		return myObj;
	}
}

Ok, let’s examine the statement Object myObj = (Object) myString; which is violating the unnecessary casting rule. There would be no reason to explicitly cast the string to an Object type since the string class already inherits from Object. Casting also bypasses the safety checks of the Java compiler and can end up causing errors at execution. The proper way to write this code would be:

class MyCastingClass {
	public Object myMethod() {
		return "Some data";
	}
}

Clean, easy to read and maintainable while preserving the rules of the compiler and creating less memory overhead. A very simple fix.

2. Eliminating Common Sub Expressions

A common mistake is the use of the same common sub-expression repeatedly in your code, yet you continue to type it out for each calculation. An Example:
int someNumber = (someValue * number1 / number2) + otherValue;
int someNumber2 = (someValue * number1 / number2) + otherValue2;

You may not realize it but you do this all the time. Performing a calculation that has a portion repeated over and over for each calculation. Because part of the calculation changes each time, you didn’t think to loop it and save yourself some trouble. Instead you are being redundant and slowing down the speed of your calculations. Here is a fix:

final int constantCalculation = (someValue * number1 / number2);
int someNumber = (constantCalculation) + otherValue;
int someNumber2 = (constantCalculation) + otherValue2;

Bingo! By placing the repeated portion of the sub-expression into a constant we can reuse it for multiple calculations without being redundant. A deceptively simple optimization.

3. Use StringBuffer (or StringBuilder) instead of String for non-constant strings.

Since strings are immutable objects and cannot change it creates a lot of overhead when you perform actions with string objects that the compiler must transform in order to interpret. Operations that appear to change string objects are actually creating new ones behind the scenes in order to perform your operation. The overhead on this becomes higher when you use String instead of StringBuffer (or StringBuilder). For Example:

class MyStringClass {
	public void myMethod() {
		String myString = "Some data";

		for (int i = 0; i < 20; i++) {
			myString += getMoreChars();
		}
	}
}	

This is the reason that the StringBuffer class exists, to provide assistance when concatenating strings since a new object would need to be created to transform the string. The new object the compiler will create is of type StringBuffer. A new string object would then be created to copy the finished string at the end of the transformation, thus creating two new objects to perform this simple step.

The difference between StringBuffer and StringBuilder is that the former is thread-safe, which is great in some cases, and an overhead in others. All StringBuffer‘s methods are synchronized. StringBuilder isn’t thread-safe and its methods aren’t synchronized, which is much more performant when you just need to use it as a local variable.

The solution would be to cut out the StringBuffer middle-man and make our own StringBuffer object so the compiler doesn’t have to:

class MyCastingClass {
	public Object myMethod() {
		String myString = "Some data";
		StringBuffer myBuffer = new StringBuffer();

		for (int i = 0; i < 20; i++) {
			myBuffer.append(getMoreChars());
		}
		myString = myBuffer.toString();
	}
}

Voila! By creating our own StringBuffer class the compiler no longer has to create one for us to do the transformation. This means there is now only one new string object being created during this process when we call the toString() method of the buffer to transfer that data to myString.

4. Use Short Circuit Boolean Operators

When making logical checks or tests in your code, the use of short-circuit evaluation will almost always speed up the time it takes to make the evaluation because the compiler does not have to check the second condition. When two expressions are joined by an OR (||) as long as the first one is true the compiler will not check the second condition, it will assume the whole statement to be true. This also works with AND (&&) where the compiler will evaluate the first state and if false, will evaluate the whole statement to false. However, the logical OR (|) does not use the short circuit evaluation.

Using || saves the compiler time by not having to check both conditions because it wouldn’t change the outcome of the statement. Here is an example of what usually happens:

class MyShortCircuitClass {
	public void myMethod() {
		if (someValue.equals("true") | someValue.equals("false")) {
			System.out.println("valid boolean");
		}
	}
}

What ends up happening in the above example is that the compiler has to check both conditions and evaluate a true or false for each even through the OR logic would have made it true if the first condition evaluated to true. Here is a better way to write these kinds of statements:

class MyCastingClass {
	public void myMethod() {
		if ("true".equals(someValue) || "false".equals(someValue)) {
			System.out.println("valid boolean");
		}
	}
}

By using short-circuit evaluation you will speed up the time it takes for the compiler to make boolean logical decisions and thus the overall processing time of your application.

Here’s a table describing four of Java’s boolean operators:

The && and || operators are short circuit operators. A short circuit operator is one that doesn’t evaluate all of its operands.

5. Use length() instead of equals() to find the length of a string

It seems to be common practice among developers that when testing for an empty string to use the equals() method, like so:

class MyStringClass {
	public boolean myTestMethod() {
		return myString.equals("");
	}
}

The problem here is the sheer overkill taking place by using equals() due to the higher overhead. The issue comes from the implementation of equals() which is designed to test if two objects reference back to the same object class. The alternative, length() (or isEmpty()), just tests to see if the references point to the same underlying object type. This is a much more efficient way if you are just testing for an empty string. You don’t care about object types or if they reference back to the same class, so quit using a sledgehammer to pound the nail. Here is how you should be testing for empty strings:

class MyCastingClass {
	public void myMethod() {
		public boolean myTestMethod() {
			// which really does myString.length() == 0 behind the schenes
			return myString.isEmpty();
		}
	}
}

Using length() provides a much more efficient method for testing for empty strings that does not require object reference overhead from the compiler.

Remember that code optimization doesn’t require fancy tricks and unreadable code. These are often simple changes that you can start making today that will speed up your processing time and make your code better. A lot of optimization is getting into the underlying processing of the compiler and understanding what is taking place in the code that you write. By learning these tips now you can begin to implement them into your solutions every time, thus making you a better developer in the process.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!

10 comments

  1. Eric Jablow says:

    In 1, since a String is an Object, just use:

    class MyCastingClass {
        public Object myMethod() {
          return "Some data";
        }
    }

    In 2., make the intent clear by using final:
    final int constantCalculation = (someValue * number1 / number2);

    In 3., remember that StringBuffer synchronizes all its methods, which is useless for local variables. Use StringBuilder instead. If you need formatting support, consider Appender.

    In 4., protect yourself against callers that accidentally send null to the method. Write the equals checks as:

    "true".equals(someValue)

    and:

    "false".equals(someValue)

    More generally, use:

    public static final Set VALID_BOOLEANS;

    static {
        Set<String> set = new HashSet<String>();
        Collections.addAll(set, "true", "false");
        VALID_BOOLEANS = Collections.unmodifiableSet(set);
    }

    // Later...
    if (VALID_BOOLEANS.contains(someValue))

    This is more flexible. You can change your list of valid strings as needed. Also, consider libraries like Google Guava or Apache Commons Collections to simplify the VALID_BOOLEANS code here.

  2. Ran Biron says:

    1. The compiler ignores those.
    2. The runtime inline those.
    3. The compiler changes String to StringBuilder concatenation. And, if at all, use StringBuilder and not StringBuffer (that forces you to almost-never needed synchronization).
    4. The runtime optimize those.
    5. Who tests string emptiness by calling equals? In all my years I’ve never seen this – not in a single codebase. And, if at all, do “”.equals(string) to avoid a nasty NPE.

    • Yup, not enough people realise what javac and JIT do for you. Got a masterclass on this during the week at Kirk Pepperdine’s Java Performance Tuning course!

    • A F says:

      Unfortunately, in the codebase I deal with, aString.equals(“”) to check if it is empty is all too common, and it’s annoying.
      Or even worse, aString.compareTo(“”) == 0

  3. itoctopus says:

    Casting is the most evil thing in any programming language. Not only it’s overhead (it takes some time to cast something) – it is the source of many nearly untraceable errors in your code. It’s a necessary and unavoidable evil though…

  4. Javed says:

    Pretty basic stuff, but good post!

  5. Michael says:

    The point about shortcircuit boolean evaluation is weird and I believe is redundant – it’s as if people are not already doing it. I’ve never, ever seen non-shortcircuit boolean being used unless it’s really intentional.

    I mean, REALLY? If someone doesn’t know shortcircuiting boolean operations (or actually any of the stuff this article is right, and is wrong about), he/she has no business doing any programming at all, because they’ll find themselves outclassed by an average high-school computer class student.

    • Michael Dorf says:

      Fair enough, Michael, thanks for your comment. Though I agree that short circuit boolean evaluation should be apparent, I’ve seen far too many cases of:

      if (awesomeStuff || !awsomeStuff && greatStuff) {

      Short circuit eval, while basic, isn’t always easy to grasp, especially if you’re just starting out in the field.

    • Matt says:

      It’s amazing how what used to be too obvious to mention is now NOT TRUE. Due to pipelining in processor i’ts often more efficient to calculate both sides of expression instead of introducing additional flow branch with shortcircuit. See https://parleys.com/play/514892280364bc17fc56c04a/chapter0/about

Comment