jqormw
Last Updated: February 25, 2016
·
6.42K
· orhanobut
62009 433414993266 4621115 n

String.substring in Android

How do you get a sub string of a string? Most frequent answer is String.subString method. But this method should be used in care. If you check the String class javadoc, you will notice that you may leak some memory because of the misusage.

String class uses Backing Array which may exceeds the string length. char[] array is implemented to store characters. For example : You have a string "hello". This string can be backed by the array {'h','e','l','l','o','w','o','r','l','d'} with offset 0 and length 5.

String.subString() method uses Flyweight pattern. Multiple Strings might share the same char[] array in order to optimize time and space complexity.

String text = "helloworld and there is one million thing inside this string";

String smallText = text.subString(0,5);

IMPORTANT: Time complexity is O(1) and no extra buffer to hold smallText.

smallText is backed by the array of text. Imagine you hold a very big string and you just want to take a very small piece of it and release it from the memory, but it won't be released. It will be retained in the memory which will cause a memory leak.

smallText object has

offset 0
length 5
chars[] points the text chars[] array {'h','e','l','l','o','w','o' ... ...}

To solve this problem you should use String copy constructor.

String text = "helloworld and there is one million thing inside this string";

String smallText = new String(text.subString(0,5));

Now smallText object has

offset 0
length 5
chars[] has a new char[] array which contains only {'h','e','l','l','o'}

IMPORTANT: Time complexity is O(n) now and an extra buffer is created.

NOTE This method is changed in jdk 7u6, now it is by default it creates a new String. Flyweight pattern is no longer valid If you compile your code with java 7.

reference : http://developer.android.com/reference/java/lang/String.html

Say Thanks
Respond