Tuesday, January 27, 2009

Weekly Source Code: Strings Are Immutable

Happy New Year 2009! :)

The String type that is actually a class in both Java and C# are immutable meaning that once you create it, it can't get changed and manipulating it will create a new string object.

This is import for when you want to populate a string in a loop (like a for loop) since everytime it will create a new string that have a performance impact on your code.

For example:

String val = null;
for (int i = 0; i < 100; i++)
{
val += i;
val += ", ";
}

The code above will create a new string object everytime for 100 times, you might not see or notice the impact but it does have a performance impact (test it if you wish).

Its better to use a string builder/buffer class and then append the string values to it since the object is only created once.

For example:

StringBuilder val = new StringBuilder();
for (int i = 0; i < 100; i++)
{
val.Append(i);
val.Append(",");
}

The above C# code use the string builder without performance impact.

Note that in C# its called the StringBuilder class where in Java its the StringBuffer class both is similar in functionality.

No comments: