6

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:

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.

George Marian
  • 2,680
  • 20
  • 21
Hari Menon
  • 33,649
  • 14
  • 85
  • 108
  • 8
    What is your question? – Ian P Jul 11 '10 at 16:01
  • So we all concluded that you shoudn't do premature optimization, maybe original question should be edited to ask to enumerate reasons of code being slow, and optimization tricks that could help when opmizing those pesky parts of slow code that needs to be fixed. I am pretty new to SO and not quite sure how to do that and what's inapropriate. Promise to chcek rules and guidelines for SO :) – Antonio Bakula Jul 11 '10 at 16:11
  • yeah.. I am just basically looking for reasons why code can be slow, according to your experience. – Hari Menon Jul 11 '10 at 17:13
  • 2
    "There are four general techniques for speeding up an algorithm: caching, compiling, delaying computation, and indexing." --Norvig, PAIP – Ken Jul 11 '10 at 19:01

9 Answers9

16

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.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • +1 for mentioning boxing/unboxing. – kirk.burleson Jul 11 '10 at 16:50
  • 3
    Programmers are notoriously bad at guessing where code hotspots are. Don't bother trying to optimze before you measure. More often than not it will be time wasted. Concentrate on good architecture. – spender Jul 11 '10 at 17:47
  • 1
    @spender: yes as bad a carpenter is at hammering in a nail without a hammer. – Brian R. Bondy Jul 11 '10 at 18:11
  • 1
    +1 for mentioning EQATEC - I've used a few, of which EQATEC has the simplest and most intuitive UI... and it presents a fairly useful analysis to boot... it just doesn't go all the way down to the line-of-code level. Sigh. – corlettk Oct 19 '12 at 12:45
8

The single most important thing regarding this question is: Don't optimize prematurely!

There is only one good time to optimize and that is when there are performance constraints that your current working implementation cannot fulfill. Then you should get out a profiler and check which parts of your code are slow and how you can fix them.

Thinking about optimization while coding the first version is mostly wasted time and effort.

chrischu
  • 3,047
  • 3
  • 27
  • 44
  • 3
    On the contrary, most substantial optimizations happen during the design phase. – peterchen Jul 12 '10 at 07:20
  • 2
    "Thinking about optimization while coding the first version is mostly wasted time and effort." Yes and no. If what you mean is piddling stuff like `++i` vs. `i++` then I agree. On the other hand, if you do much optimizing, you learn to avoid the patterns that lead to poor performance in the first place, namely, overblown data structure design, over-reliance on notifications, excessive abstraction, leading to broccoli-type call trees. – Mike Dunlavey Jul 12 '10 at 13:01
5

"I would rather choose fast-executing dirty code over something which might be more elegant or clean, but slower."

If I were writing a pixel renderer for a game, perhaps I'd consider doing this - however, when responding to a user's click on a button, for example, I'd always favour the slower, elegant approach over quick-and-dirty (unless slow > a few seconds, when I might reconsider).

I have to agree with the other posts - profile to determine where your slow points are and then deal with those. Writing optimal code from the outset is more trouble than its worth, you'll usually find that what you think will be slow will be just fine and the real slow areas will surprise you.

Will A
  • 24,780
  • 5
  • 50
  • 61
3

One good resource for .net related performance info is Rico Mariani's Blog

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
DanP
  • 6,310
  • 4
  • 40
  • 68
2

IMO it's the same for all programming platforms / languages, you have to use profiler and see whitch part of the code are slow, and then do optimization on that parts.

While these links that you provided are valuable insig don't do such things in advance, measure first and then optimize.

edit:

http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html

When to use StringBuilder?

At what point does using a StringBuilder become insignificant or an overhead?

Community
  • 1
  • 1
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
2

There are lots of tricks, but if that's what you're thinking you need, you need to start over. The secret of performance in any language is not in coding techniques, it is in finding what to optimize.

To make an analogy, if you're a police detective, and you want to put robbers in jail, the heart of your business is not about different kinds of jails. It is about finding the robbers.

I rely on a purely manual method of profiling. This is an example of finding a series of points to optimize, resulting in a speedup multiple of 43 times.

If you do this on an existing application, you are likely to discover that the main cause of slow performance is overblown data structure design, resulting in an excess of notification-style consistency maintenance, characterized by an excessively bushy call tree. You need to find the calls in the call tree that cost a lot and that you can prune.

Having done that, you may realize that a way of designing software that uses the bare minimum of data structure and abstractions will run faster to begin with.

Community
  • 1
  • 1
Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135
0

If you've profiled your code, and found it to be lacking swiftness, then there are some micro-optimizations you can sometimes use. Here's a short list.

Micro-optimize judiciously - it's like the mirror from Harry Potter: if you're not careful you'll spend all your time there and get nothing else done without getting a lot in return.

The StringBuilder and exception throwing examples are good ones - those are mistakes I used to make which sometimes added seconds to a function execution. When profiling, I find I personally use up a lot of cycles simply finding things. In that case, I cache frequently accessed objects using a hashtable (or a dictionary).

Charlie Salts
  • 13,109
  • 7
  • 49
  • 78
  • 1
    "Micro-optimize judiciously - it's like the mirror from Harry Potter" -- wow, I think I'm now officially too old to be a programmer. :-) – Ken Jul 11 '10 at 18:56
0

Good program architecture give you a lot better optimization, than optimized function.
The most optimization is to avoiding all if else in runtime code, put them all at initialize time.
Overall, optimization is bad idea, because the most valuable is readable program, not a fast program.

Avram
  • 4,267
  • 33
  • 40
0

http://www.techgalaxy.net/Docs/Dev/5ways.htm has some very good points... just came across it today.

Hari Menon
  • 33,649
  • 14
  • 85
  • 108