Deep dive towards improving C# code efficiency and productivity

I have collected few tips & standard coding practices for those who believe in delivering quality in work they do, after walking through most of the software applications & their code.

Following are the points we can consider while coding.

1. Choose your data type before using it. Don’t use var, if you know data type of data you are going to store in variable. Because compiler need to take extra care while compiling application.

2. Use For loop instead of foreach

If you check assembly code for for & foreach loops,

you ‘ll find extra MOVE Register1, Register2 statements for foreach loop.
Try to avoid foreach

3. Choose when to use a class and when to use a structure

Class is reference type & structure is value type. Use them carefully by considering the memory utilization.

4. Always use Stringbuilder for String concatenation operations

Because stringbuilder use same object while concatenating strings, while other concatenation ways create new object & do copy in object & append to it operation.

5. Choose best way to assign class data member

Consider design patterns, static classes, base class, sealed class, interfaces. Try to follow SOLID principle while designing.

6. Static Methods

Non-inlined instance methods are always slower than non-inlined static methods. To call an instance method, the instance reference must be resolved, to determine what method to call. Static methods do not use an instance reference.

If you look at the intermediate language, you will see that static methods can be invoked with fewer instructions.

7. Constants

Constants are not assigned a memory region, but are instead considered values.

8. Static fields

Static fields are faster than instance fields, for the same reason that static methods are faster than instance methods. When you load a static field into

memory, you do not need the runtime to resolve the instance expression.

9. Switch.

You will find that the switch statement compiles in a different way than if-statements typically do. For example, if you use a switch on an int, you will often get jump statements, which are similar to a computed goto mechanism.

Note:

Using jump tables makes switches much faster than some if-statements. Also, using a char switch on a string is fast.

10. ToString()

It is poor programming to use the ToString method when it is not needed. Sometimes, developers will call ToString on a character in a string, and then test it against a single-character string literal. This is inefficient.

Instead:

Use a character testing expression with two chars. Please reference the specific article on this topic for more details.

11. Use Ternary (?:) || Null-Coalesce (??) ?. Operator

12. Use string.IsNullOrEmptyOrWhiteSpace(s)

13. Use the Convert class which supports full Data Type conversion between all data types.

14. using statements – It handles object dispose.

using (System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create())

15. Use Namespace Alias Qualifier

using Excel = Microsoft.Office.Interop.Excel;

16. Object initialization

Child child = new Child() { Age = 10, Name = “Bryan”, StreetAddress = “Seattle, WA 98124” };

17. Use Try-Catch-Finally blocks

18. Use ApplicationEnd_Request event to route user to relevant error pages based on statuscode instead of yellow errorpages.

protected void Application_EndRequest()

{

int statusCode=Context.Response.StatusCode;

switch(statusCode)

{

Case 404:

Response.Clear();

HttpContext.Current.Response.Redirect(“~/Error/PageNotFound”);

break;

Case 500:

Response.Clear();

HttpContext.Current.Response.Redirect(“~/Error/ServerError”);

break;

}

}

19. In Application_Errror event collect & log application Error

var ex=Server.GetLastError()
20. Use Use && and || operators

21. Avoid Destructors

Empty destructors should not be used. When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this simply results in a loss of performance.

22. Interface driven coding

Have a look at following GitRepo for C# 6.0 & C# 7.0 new features.

https://github.com/agnihotriketan/csharp7Features

https://github.com/agnihotriketan/cSharp6Feature

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s