One of the most common mistake we do with Strings is when we try to concatenate multiple strings to form a bigger string. There are a lot of cases where we try to build a large string like, building a large json string to be passed, building a html, building a bulk insert sql, etc., In majority of cases we would be looping to create the large string.
In this experiment we shall try to create a large string which will contain “hello world” 20000 times.
Version 1:
String largeString = “”;
for(int i = 0 ; i < 20000; i++)
{
largeString = largeString + “hello world”;
}
The code might look alright, let us see how it performs
It took almost 186 Seconds to complete the operation in my PC (P4 3.04GHz, 1GB RAM)
For such a small operation it took more than 3 minutes to complete, surprising?
Let us experiment with another implementation using StringBuilder
Version 2:
StringBuilder largeStringBuilder = new StringBuilder();
for(int i = 0 ; i < 20000 ; i++)
{
largeStringBuilder.append(“hello world”);
}
This code took 15 ms to build the same string. Please notice it is not 15 seconds it is 15 milli seconds. That is almost 12400X faster than the string concatenation done in version 1 of the code.
Source: Codeexperiments
No comments:
Post a Comment