I have a for loop like this :
String myString = "123456789";
String prefix = null;
for (int i=6;i>=0;--i)
{
prefix = myString.substring(0,i);
process(prefix);
}
The problem is that if this block of code is executed N times, N*7 strings will be created (7 strings will be created for each execution – because the substring method creates a new String and this method is called 7 times for each execution).
I’m thinking about how to improve performance in this case. I wanted to know if there is a way to use only one String per execution with this being modified each time. That’s the purpose of the StringBuilder, but i think the StringBuilder doesn’t help in this case :
String myString = "123456789";
StringBuilder prefix = new StringBuilder(myString);
for (int i=6;i>=0;--i)
{
prefix.delete(i,prefix.length());
process(prefix.toString());
}
In this case, prefix always reference the same StringBuilder object, but the same problem appears at another place because prefix.toString() returns always a new String object.
Any idea?
(I know that the topic has been treated many times. But i’ve done some search and i didn’t find solution, maybe that’s the minimal use of memory?)
Thanks for your help
While it is true that
myString.substring(0, i)creates a newStringobject, please note that this does not copy the underlying character data.Before doing anything to this code, I would use a profiler to verify that this is indeed a bottleneck (either in terms of CPU usage, or in terms of strain placed on the garbage collector).