Pages

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)

Monday, March 11, 2013

Using Traceview for better performance

As some of you might already know, I'm starting a series of posts on optimizing Android apps for my thesis. In this post here, I'm going to give quick preview of how to use Traceview and why it's a great tool to use.

TraceWhat?

What is Traceview and why should I use it? These are the two questions we're going to start with. According to the Android Developers website, Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance.
Basically what it does is it shows you what part of your code is using the CPU a lot. So that already covers the 'what'-part, now let's continue to the why part.

Why should we be interested in knowing how much CPU-time my awesome method needs to run? It's all about performance. Performance is one of the most important topics to focus on, especially in mobile development.We all want our app to be the fastest in the whole Play Store, don't we? By using Traceview properly, we can get a nice graph, showing us what part of our code is slowing down the app the most. Once we know this, we know where to start looking for better performance and get our app running twice as fast. I'll show you in an example below.

Example

For this small example, I'm going to write a simple app that does nothing. Well, nothing interesting that is. This is the code I'm going to run in the doInBackground() method of an AsyncTask.


String result = "";

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

 String number = String.valueOf(i);

 result += number;

}

Basically, it just makes on really long String (012345678910111213...).

Now how are we going to make sure that Traceview checks this part of the code? Really simple. All we have to do is add the next two lines somewhere in the beginning and at the end of our code:

Debug.startMethodTracing("bonappetit");

//...

//OUR CODE COMES HERE

//...

Debug.stopMethodTracing();

This will create a file called bonappetit.trace on the SD card of the device. Everything that happens between those two lines of code will be recorded in that file. I've started tracing ath the beginning and the end of the doInBackground() method.
IMPORTANT NOTE: Don't forget to add the permission in the manifest for writing to the SD card!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If we open the DDMS perspective in Eclipse, we can have a look at the files on our plugged-in device (or emulator). Select the device on the left side, then go to 'File Explorer' and look into the sdcard-folder for the file. (Mine was under /storage/sdcard0/). Once selected we can click 'Pull a file from the device'. Save the file somewhere on your computer.
Next use your command prompt and go to the folder of your android-sdks. Continue into the tools-folder and type the command 'traceview' followed by the file we just pulled from the device.



If we have a look at the results, we notice that almost 27% of the time was spend on StringBuilder <init>.
In the upper right corner we can see that the whole process took about 800ms, so that's more than 200ms.
If we have a look at our code we can see that we are actually creating a new String object every time in the for-loop. This is why the app spends so much time on StringBuilder <init>.

Now how can we make this better? As a good developer, you should know that using new String objects for creating one long string, isn't a good idea. Java has a class called StringBuilder. Let's try to change our code a bit like this and run the Traceview tool again:

StringBuilder sb = new StringBuilder(4000);

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

 sb.append(String.valueOf(i));

}

String result = sb.toString();


If we look in the upper right corner again this time, we can see that the whole process now only took 332ms.
This is more than twice as fast. It is possible to speed this process up even more, but always ask yourself "Does it have to be faster?". Don't waste time on optimizing things that don't need further optimization!

This was an example of Java-optimization, but because Android = Java, I'll make a post on this sort of code optimization as well. Feel free to leave comments below.

Try this out, it could be a great tool for you to use!



source: www.parleys.com

Wednesday, March 6, 2013

Small Introduction to Android Optimization

Hi guys,

In the next couple of months I'll be writing my thesis on "Optimizing Android Apps: Tips for better usability, performance and battery life". Since I'll probably will be discussing a lot of different topics, I'll be posting some of my ideas and experiences here. First of all because I wouldn't want to keep you from using this information for better development, but mostly because I'm very much interested in the comments of other developers. My thesis will be written in Dutch but I'll translate the topics to English for this blog.

Why, where and when?

When I started looking for information on the web, I saw a lot of presentations on this subject. After watching them all, I realized all of them start with global view about Android and what makes one app better than another. The way I see it, you can ask yourself three simple questions: Why, where and when?

Why should we spend time optimizing our apps? They work fine, all of the requested features are implemented. The device is able to do what it should do. Well actually, this is great. Especially if you have developed an app that does something no other app can do. Unfortunately, this is usually not the case.
By now, there are probably around 750.000 apps for Android available. The chances of creating a completely new app are rather small. So there is definitely a lot of competition. 

The thing that developers want is for their app to be downloaded, a lot. It's your task to make sure that your app is better than those other 10 that do exactly the same thing.
The thing that the user wants is to be able to do something with a certain application without wasting time. This 'wasting time' can happen on different levels, whether it's waiting for something to process, having to run through a lot of different screens before reaching the right one or even having to recharge the phone because its battery is draining really fast. As exemplary developers, it is our duty to give the user the best possible experience when using an Android app.

Getting featured

There is one thing almost all Android developers have in common. They all want their app to get featured. Once an app gets featured on Google Play, it can easily be downloaded 10 times as much in only a day. The problem is, there are only a small number of apps that get featured. The bar is set pretty high but the bigger the effort, the bigger the reward.

Now we know why we should spend time for optimization, it's important to know where you should be optimizing. First of all, mobile devices are in many ways different from PC's, but the most important difference is their limited resources such as battery life, data traffic, memory and storage

For the device to work properly, we should make sure our apps respect these limitations. Many devices, especially low-end devices, can take a lot more time for processing data. If we make sure that our app doesn't use unnecessary memory, we can easily speed this up.
We have also have to keep this principle in mind when we are getting data from the network. Most users have a limited data plan on their mobile phones and they don't want to pay anything extra at the end of the month.

But if you ask me, the most important issue of mobile phones is battery life. Every user expects their device to make it through the day without have to plug it in. This has always been a problem with smartphones so it's our job, as exemplary developers, to keep the battery from draining too fast. I will probably be focusing on this topic the most.

Having said that, there is only one question that remains. When should I optimize my application?
"Premature optimization is the root of all evil" - Donald Knuth
Now what do I mean by that? Simple, only start thinking about optimizing when your application does what it has to do. If you don't you'll start to lose way too much time on optimizing some process that doesn't really need to be optimized.

Use tools. Android provides a number of tools that you can use to check where your app needs optimization, but in order to use it, you have to be able to test your code.


That's all for now, guys. Starting next week, I'll be posting my first, more practical, tips on Android optimization. Thanks for reading and be sure to check out my other posts on Google Maps API v2.

Stay tuned for more!