Basic Tips For Application Performance Optimization | Java

Hello everyone! In this story, I want to give a brief introduction to how we can improve our application performance. There are many OS versions which developers find hards to keep up when it comes to development. Each system has different aspects regarding hardware or software making it development a nightmare.

To ensure your app performance well across a wide variety of systems, ensure your code is efficient at all levels and optimize your performance.

Below are the factors which can slow down the app performance and improvements.

Usage Enhance for loop syntax

The enhanced loop (also known as foreach loop) control flow statement for traversing items in a collection. With the collection, an iterator is allocated to make calls to next()and hasNext()

Let’s take a look at different alternatives for iterating through an array.

static class Student {
    int age;
    int marks;
}

Studen[] mArray = ...

public void first() {
    int totalAllStudentMarks = 0;
    for (int i = 0; i < mArray.length; ++i) {
        totalAllStudentMarks += mArray[i].marks;
    }
}

public void second() {
    int totalAllStudentMarks = 0;
    Student[] localArray = mArray;
    int len = localArray.length;

    for (int i = 0; i < len; ++i) {
        totalAllStudentMarks += localArray[i].marks;
    }
}

public void third() {
    int totalAllStudentMarks = 0;
    for (Student a : mArray) {
        sum += a.marks;
    }
}

first(): It is slow because of the cost of getting the array length once for every iteration through the loop.

second(): It is faster it pulls everything out into local variables avoiding the look-up. There’s array length offers a performance benefit.

third(): It is fastest from both of them, it uses the enhanced for-loop introduced in Java 1.5 version.

Avoid Creating Unnecessary Objects

As you allocate more objects in your app you will force a periodic garbage collection. The concurrent garbage collection introduced, but unnecessary work will always be avoided.


  • Always creates an array of int instead of creating an array of Integer objects. The int is a wrapper class of Integer. Two parallel arrays of int are also a lot more efficient than an array of (int, int) objects. The same goes for any combination of primitive types.
  • When returning a String from a method is always appended StringBuffer to anyway, change your function signature and implementation so that it does not append directly, instead of creating a short-lived temporary object.
  • Do not create a new instance of String, an example is below.
// Don't do this
String s  = new String("Bad way to creating a string");

// Create a String like this
String s = "Hey there";

Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects creation means less frequent garbage collection.

Reusing mutable objects

We need to reuse our objects if we know they can’t be modified. The following shows the example.

class Person {
  String name;
  Calendar bornDate;

  public int getCurrentAge() {
      Calendar currentDate = Calendar.getInstance()
      int years = currentDate.get(Calendar.YEAR) - bornData.get(Calendar.YEAR)
      return years;
  }
}

You see the getCurrentAge method always create a new instance of Calendar every-time it is invoked. So, how we can avoid unnecessary object creation. Below is the example is a modified example of Person class.

class Person {
  String name;
  Calendar bornDate;
  private static final Calendar currentDate = Calendar.getInstance();

  public int getCurrentAge() {
     int years = currentDate.get(Calendar.YEAR) - bornDate.get(Calendar.YEAR);
     return years;
  }
}

 

Prefer static over virtual

If you don’t need to access an object field, make your method static. An invocation will be about 15% to 20% faster.

Avoid using floating point

The floating-point is about 2x slower than an integer. In speed terms, there’s no difference between float  and double on the more modern hardware. On desktop machines space is not an issue so you should prefer double to float.

Use static final for constants

Fields with the static final go into dex file. Whenever the constants fields are required it will use relatively inexpensive “string constant” instruction instead of a field lookup.

Eliminate obsolete object reference

An obsolete reference is one that is kept around but will never be used, preventing the object it refers to from being eligible for garbage collection, thus causing a memory leak. The best way to eliminate the obsolete reference by falling it out of scope.

Define each variable in the narrowest possible scope.

Don’t just start measure

Before you start optimizing, make sure you have a problem that you need to solve. Make sure you can accurately measure your existing performance or you won’t be able to measure the benefits of the alternative you try.

Alright, guys, this was all from performance optimization article. I know there’s a lot more which I miss in this article but I’m just a beginner like you guys. I write what I learned. Please let me know what did I miss in this article.

My new article Ten Simple Rules For Best Programming Practices.

Thank you for being here and keep reading…

LEAVE A REPLY

Please enter your comment!
Please enter your name here