Archive for the ‘Object Oriented’ Category

Code practice – String usage in .NET

April 6, 2009 3 comments

String in .Net, is an Immutable object (Object cannot be modifed). Hence memory allocated for a string remains even if you alter/modify the string through code, forcing the CLR to create new space for the modified string.

//Code Illustration in C#.Net

string str = ""; //memory created for str and value "" is stored
str = "String is Immutable" //new memory space is allocated for str
                            //and value is stored
str += str  + " in .NET" //Again, new memory allocation

This means more string operation you do with, more memory is occupied, though its with the same string variable. Better approach would be to use StringBuilder to do all appends and get the final output as StringBuilder class provides an efficient way to append. And its mutable.

Also string str = “” and string str = String.Empty is not the same in terms of memory allocation. the first creats an object in the memory and the latter does not. Hence prefer the latter

Avoid ToLower() and ToUpper() in code (Remember strings are immutable)

–Writing code is easy, writing good code is not.  Learn, Implement, Share–