C# code optimization

1. Use of StringBuilder

Many times, we needed to modify string. Like we needed to append some text to a string.

E.g. string s = “First”; /*Here, New string will be created in memory and address of the memory location will be assigned to variable s.*/

s = s + “Second”; /*It won’t modify existing string (string is immutable) but it will create new string with value “FirstSecond” and new memory location will be assigned to variable s.*/

So if we wanted to modify a string, we should always use StringBuilder class. This will not create new string but modify existing one. See below example.

StringBuilder sb = new StringBuilder(“First”);
sb.Append(“Second”);

2. Use For loop instead of foreach

Foreach uses more space than for loop. Internally, it uses Next() and GetEnumerator() method of IEnumerable. So if you want clean code / readable code then go for foreach but if you want performance then go for for loop.

3. Use struct instead of class

Many times, for less number of fields / properties, we directly create class. However, its recommended by Microsoft that we should use Struct for less number of properties / field. Reason is struct is value type and stored in stack so it means this won’t be stored in Heap and garbage collection won’t come in picture.

4. Use List instead of ArrayList

ArrayList can contains any object. It may be string, int or any complex object. While iterating over these objects, we need to cast each object to its own type to work on it. So over here, we have overhead of casting from object to particular type. Instead we should use List where T can be any value type or complex type. Its a generic list so no need of casting while iterating over these generic list.

Leave a Reply

Your email address will not be published. Required fields are marked *