Monday 24 February 2014

Optimize your C# Code

Many of us are not tacking our code writing skill seriously, because of that we always get firing during Code review. Then we need to work on code optimization. So; better to write code in optimized way right from initial stage.

Below are few techniques.

1. Learn when and how to use StringBuilder
You must have heard many times before that a StringBuilder is much faster at appending strings together than normal string types.

Well fact is StringBuilder is faster typically with big strings. It means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.

However if you just want to append something to a string a single time; then StringBuilder class is overkill. So; in this case simple string variable improves resources use and readability of your code.

Conclusion is simply choosing correctly between StringBuilder objects and string types you can optimize your code.


2. Use string.Empty

This shall not give you much performance improvement but just for readability improvement, but it still counts as code optimization.
So, if you are comparing string variable whether with empty text then it’s better to compare with string.Empty.

if (str == "")

Preferred is:
if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.
However, checking a string's length to be ‘0’ is faster than comparing it to an empty string. But you need to see what fits your requirement of code/logic.

3. Replace ArrayList with List<>
ArrayList are useful when storing multiple types of objects within the same list. However, if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.

Take the following example:

ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

If you notice; above ArrayList only contains interger values. So using a List<> class is can be lot better.
To convert it to a typed List, only the variable types need to be changed:

List<int> intList = new List<int>();
intList.add(10)
return intList[0] + 20;

Notice that there is no need to cast types with List<>. So the performance increase can be significant.

4. Use && and || operators
When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go through the statements one at a time and stop as soon as the condition has either been met or not met.

Executing less code is always a performance benefit but it also can avoid run-time errors, consider the following C# code:

if (object1 != null && object1.runMethod())
If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

5. Smart Try-Catch
Try-Catch statements are meant to catch exceptions that are beyond the programmers’ control.
But it’s been see that programmer’s are using generic exception all the time, start using specific exceptions instead.

E.g. if you are performing mathematical calculation and expecting exception in that, then use Arithmetic exception instead of “Exception”
Also if expecting silly errors like “divide by 0” then better to check that in a condition rather than letting handled by exception.

6. Replace Divisions
C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.

About Author:
Harshad Pednekar is budding technology geek, who actively contributes toSystems Plus with his creativity and research on technology. To read more interesting articles from him, please follow: http://harshadpednekar.blogspot.in

5 comments:

  1. THANK YOU FOR THE INFORMATION
    PLEASE VISIT US
    erp softwares








    ReplyDelete
  2. If somebody comes along selling something that will satisfy my needs, then I will be more than happy to part with my hard-earned money. SEO Antwerpen

    ReplyDelete
  3. Photovoltaic cells generate electricity from sunlight, but there are other methods for making solar energy. You can also get solar-thermal panels which heat water as opposed to creating electricity. Solar-thermal panels work differently than PV panels, and don't involve electricity. www.zonnepanelen-soloya.nl/service/zonnepanelen-kopen

    ReplyDelete
  4. This variation in income per client can be attributed to the type of services provided as well as the depth of services. The size of business a client is seeking SEO services for also play a role in determining the amount to be charged. SEO zoekmachine optimalisatie

    ReplyDelete
  5. Installation costs for solar energy systems are high, although there are different grants available to help finance solar technology. A much more reasonably priced option is to assemble your own solar panels. Zonnepanelen plaatsen

    ReplyDelete