StringBuilder or String Concatenation.. Which is better ?
How they work ?
String is immutable while StringBuilder is mutable.
After a string object is created its value cannot be changed. Then how
name ="jimmy"+"augustine" is possible ? When we assign this , we actually discard the old string object and create a new string.
But StringBuilder is mutable. StringBuilder class provides methods to change its contents at anytime.StringBuilder has a very useful method "append" to add new strings to the end of the existing string. StringBuilder internally reserves a certain amount of memory(Buffer). When a new string is added to the StringBuilder, the new string is just copied to the existing buffer. If the buffer is not enough to fit the new string , then a new buffer is created to fit the new string.
My Performance Test ( StringBuilder VS Concatenation):
Here is a simple performance test which demonstrate the power of stringBuilder over string concatenation.
DateTime start;
start = DateTime.Now;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < strbuilderexecutiontime =" DateTime.Now" builder ="" start =" DateTime.Now;" str =" string.Empty;">for (int i = 0; i <>
{
str = str + i;
}
strBuilderExecutionTime =DateTime.Now - start ;
Console.WriteLine("Exection Time for Concatenation =" + strBuilderExecutionTime.ToString());
Output :
Execution Time for string builder =00:00:00.0312500
Execution Time for Concatenation =00:01:18.5937500
When looking at the output of the code , it is very clear that StringBuilder is much more efficient than the regular concatenation.
Is there any disadvantage for StringBuilder when comparing with String concatenation ?
Is StringBuilder always a better Option than concatenation ? No... Because creating a StringBuilder object using the constructor will take time. So if there is only few concatenations ( say less than 5 apprx) , then no need to go for StringBuilder.
Conclusion:
If the number of concatenations is more , then use StringBuilder. But if the number of concatenations is very few then go for ordinary "+" concatenations.
If the number of concatenations is more than 8, then in all the situations StringBuilder is faster than String concatenations.
No comments:
Post a Comment