Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to improve efficiency of C# code [closed]

Like most of us, I am a big fan of improving efficiency of code. So much so that I would rather choose fast-executing dirty code over something which might be more elegant or clean, but slower.

Fortunately for all of us, in most cases, the faster and more efficient solutions are also the cleaner and the most elegant ones. I used to be just a dabbler in programming but I am into full-time development now, and just started with C# and web development. I have been reading some good books on these subjects but sadly, books rarely cover the finer aspects. Like say, which one of two codes which do the same thing will run faster. This kind of knowledge comes mostly through experience only. I request all fellow programmers to share any such knowledge here.

Here, I'll start off with these two blog posts I came across. This is exactly the kind of stuff I am looking for in this post:

  • Stringbuilder vs String performance analysis
  • The cost of throwing an exception

P.S: Do let me know if this kind of thing already exists somewhere on this site. I searched but couldn't find, surprisingly. Also please post any book you know of that covers such things.

P.P.S: If you got to know of something from some blog post or some online source to which we all have access, then it would be better to post the link itself imo.

like image 875
Hari Menon Avatar asked Jul 11 '10 15:07

Hari Menon


People also ask

Why C is efficient?

low level languages - and C is one - allow less advanced constructs and are thus closer to assembler and easier for the compiler to optimize. By more efficient,does it mean the machine code is better,or it takes less time to be 'translated' into machine code?


1 Answers

There are some things you should do like use generics instead of objects to avoid boxing/unboxing and also improve the code safety, but the best way to optimize your code is to use a profiler to determine which parts of your code are slow. There are many great profilers for .NET code available and they can help determine the bottlenecks in your programs.

Generally you shouldn't concern yourself with small ways to improve code efficiency, but instead when you are done coding, then profile it to find the bottlenecks.

A good profiler will tell you stats like how many times a function was executed, what the average running time was for a function, what the peak running time was for a function, what the total running time was for a function, etc. Some profilers will even draw graphs for you so you can visually see which parts of the program are the biggest bottleneck and you can drill down into the sub function calls.

Without profiling you will most likely be wrong about which part of your program is slow.

An example of a great and free profiler for .NET is the EQATEC Profiler.

like image 167
Brian R. Bondy Avatar answered Oct 28 '22 13:10

Brian R. Bondy