Monday, March 18, 2013

Optimizing your Java code in Android (Part 1)

Hi guys,
This post is a follow-up from my last post on using Traceview for better performance. I explained how to use Traceview to find out which part of the code is slowing down your app. In the example I've written a small method in two ways, a bad way and a better way. Using Traceview we could monitor the usage of the CPU and compare the two parts of code.

I've explained some principles of optimizing your Java code in there. That is:

  • Don't initialize objects in a loop
  • Avoid String concatenation in a loop
  • Use StringBuilder to build a large String.
In this post I'll take some other of these principles for good Java-coding, put them in a small app and compare 'the good way' with 'the bad way' using Traceview.

Use System.arraycopy

In this first example, I've compared two ways of copying an array. First by using a loop, then by using System.arraycopy(). This is the code I've used in the first way:

int[] array = new int[100000];

int l = array.length;

for(int i=0;i<l;i++){

 array[i] = i;

}

  

Debug.startMethodTracing("bonappetit");

int length = array.length;

int[] copy = new int [length];

for(int i=0;i<length;i++)

{

 copy [i] = array[i];

}

Debug.stopMethodTracing();

And this is the code that does the same thing.

Debug.startMethodTracing("bonappetit");

int length = array.length;

int[] copy = new int [length];

System.arraycopy(array, 0, copy, 0, length);

Debug.stopMethodTracing();

I've monitored the both processes with Traceview and saw that the second method ran 3 times as fast.

(To be continued very soon)