Wednesday, July 25, 2007

Effective C# mechanisms

Effective C# mechanisms:

1. Use 'as' and 'is' keywords instead of casting.

the ‘as' and ‘is' keywords instead of casting. It's true that those keywords let you test runtime type information without writing try / catch blocks or having exceptions thrown from your methods. It's also true that there are times when throwing an exception is the proper behavior when you find an unexpected type. But the performance overhead of exceptions is not the whole story with these two operators. The as and is operators perform run time type checking, ignoring any user defined conversion operators. The type checking operators behave differently than casts.
runtime performance as one justification for choosing among different language constructs, it's worth noting that very few Effective Items are justified strictly based on performance. The simple fact is that low-level optimizations aren't going to be universal. Low level language constructs will exhibit different performance characteristics between compiler versions, or in different usage scenarios. In short, low-level optimizations should not be performed without profiling and testing.

2.String Concatenation is expensive
string concatenation is an expensive operation. Whenever you write code that appears to modify the contents of a string, you are actually creating a new string object and leaving the old string object as garbage.

3.Checking the Length property is faster than an equality comparison
Some people have commented that this idiom:
if ( str.Length != 0 )
is preferable to this one:
if ( str != "" )
The normal justification is speed. People will tell you that checking the length of the string is faster than checking to see if two string are equal. That may be true, but I really doubt you'll see any measurable performance improvement.

4.String.Equal is better than == ( Refer gnana prakash anna's article)
5.Boxing and Unboxing are bad

This is true, boxing and unboxing are often associated with negative behaviors in your program. Too many times, the justification is performance. Yes, boxing and unboxing cause performance issues.