After reading the android documentation about String, which includes this:
This class is implemented using a char[]. The length of the array may
exceed the length of the string. For example, the string “Hello” may
be backed by the array [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’. ‘o’, ‘r’, ‘l’,
‘d’] with offset 0 and length 5.Multiple strings can share the same char[] because strings are
immutable. The substring(int) method always returns a string that
shares the backing array of its source string. Generally this is an
optimization: fewer character arrays need to be allocated, and less
copying is necessary. But this can also lead to unwanted heap
retention. Taking a short substring of long string means that the long
shared char[] won’t be garbage until both strings are garbage. This
typically happens when parsing small substrings out of a large input.
To avoid this where necessary, call new
String(longString.subString(…)). The string copy constructor always
ensures that the backing array is no larger than necessary.
So my question is : What happens when we create a String as the substring of a StringBuilder? Are there any memory considerations as well?
Which leads to my other question :
Is the combo StringBuilder / String a good choice when selecting small parts of a large text and programming with rapidity considerations in mind?
Thank you for your attention and your time, have a good day!
Here: AbstractStringBuilder.substring(int, int) (StringBuilder extends this class) in OpenJDK does exactly what’s described in your snippet: creates a new String to avoid retaining the memory for the whole string substring was called on. Let us hope that Dalvik’s implementation is the same 🙂
Actually, you get the idea how to check this, here are instructions on how to get Dalvik sources: http://source.android.com/source/downloading.html