Android Performance — Part 1

Wajid Ali
2 min readJun 28, 2021

String VS StringBuilder

Let’s say that you have a String, and for some reason, you want to append more Strings to it 10 thousand times. The code could look something like this.

String string = "hello";
for (int i = 0; i < 30000; i++) {
string += " world";
}

You can see on the Android Studio Monitors how inefficient some String concatenation can be. There are tons of Garbage Collections (GC) going on.

This operation takes around 22 seconds on my fairly good device, which has Android 5.1.1. The more efficient way of achieving the same goal is using a StringBuilder, like this.

StringBuilder sb = new StringBuilder("hello");
for (int i = 0; i < 30000; i++) {
sb.append(" world");
}
String string = sb.toString();

On the same device, this happens almost instantly, in less than 15ms. The CPU and Memory visualizations are almost totally flat, so you can imagine how big this improvement is. Notice though, that for achieving this difference, we had to append 10 thousand Strings, which you probably don’t do often. So in case you are adding just a couple of Strings once, you will not see any improvement. By the way, if you do:

String string = "hello" + " world";

It gets internally converted to a StringBuilder, so it will work just fine.

You might be wondering, why is concatenating Strings the first way so slow? It is caused by the fact that Strings are immutable, so once they are created, they cannot be changed. Even if you think you are changing the value of a String, you are actually creating a new String with the new value. In an example like:

String myString = "hello";
myString += " world";

What you will get in memory is not 1 String “hello world”, but actually 2 Strings. The String myString will contain “hello world”, as you would expect. However, the original String with the value “hello” is still alive, without any reference to it, waiting to be garbage collected. This is also the reason why you should store passwords in a char array instead of a String. If you store a password as a String, it will stay in the memory in human-readable format until the next GC for an unpredictable length of time. Back to the immutability described above, the String will stay in the memory even if you assign it another value after using it. If you, however, empty the char array after using the password, it will disappear everywhere.

If you have liked the article, follow for more to come. Your clap would be a very nice token of appreciation.

--

--

Wajid Ali

Android, iOS, Flutter, Augmented Reality and Technology enthusiast.