akdom
akdom

Reputation: 33149

Improve speed performances in C#

This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:

Please stay away from general optimization techniques unless they are C# specific.

This has previously been asked for Python, Perl, and Java.

Upvotes: 21

Views: 19845

Answers (18)

Mutation Person
Mutation Person

Reputation: 30488

Dynamic typing is going to cause a huge performance hit. If you can avoid it, then I'd suggest doing so.

Take the following statically typed code:

var obj = new MyClass();
obj.test = "test";
Console.WriteLine(obj.test);

public class MyClass
{
    public string test {get; set;}
}

When I run it through LinqPad, I see 27 lines of IL Generated:

Linqpad Static C#

But, the following statement, which does much the same thing spits out around 100:

dynamic sampleObject = new ExpandoObject();
sampleObject.test = "test";
Console.WriteLine(sampleObject.test);

Upvotes: 0

GWLlosa
GWLlosa

Reputation: 24403

Caching items that result from a query:

private Item _myResult;
public Item Result
{
     get
     {
          if (_myResult == null)
          {
               _myResult = Database.DoQueryForResult();
          }
          return _myResult;
     }
}

Its a basic technique that is frequently overlooked by starting programmers, and one of the EASIEST ways to improve performance in an application.

Answer ported from a question that was ruled a dupe of this one.

Upvotes: 0

Winston Smith
Winston Smith

Reputation: 21884

I have the following MSDN article bookmarked, and find it to be a good general reference.

Improving .NET application pefformance

Upvotes: 1

Lurker Indeed
Lurker Indeed

Reputation: 1531

For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:

protected override System.Windows.Forms.CreateParams CreateParams { 
    get { 
        CreateParams cp = base.CreateParams; 
        cp.ExStyle = cp.ExStyle | 0x2000000; 
        return cp; 
    } 
} 

Upvotes: -1

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

This is true for any language, not just C#

  1. For an existing app, don't do anything until you know what's making it slow. IMHO, this is the best way.

  2. For new apps, the problem is how programmers are taught. They are taught to make mountains out of molehills. After you've optimized a few apps using this you will be familiar with the problem of what I call "galloping generality" - layer upon layer of "abstraction", rather than simply asking what the problem requires. The best you can hope for is to run along after them, telling them what the performance problems are that they've just put in, so they can take them out as they go along.

Upvotes: 0

piers7
piers7

Reputation: 4404

Use a decent quality profiler and determine where your bottlenecks are.

Then start asking how to improve performance.

Anyone who makes any blanket statements like 'avoid reflection' without understanding both your performance profile and your problem domain should be shot (or at least reeducated). And given the size of the .Net landscape it's pretty much meaningless to talk about C# optimization: are we talking about WinForms, ASP.Net, BizTalk, Workflow, SQL-CLR? Without the context even general guidelines may be at best a waste of time.

Consider also what you mean by 'speed it up' and 'improve performance'. Do you mean greater resource efficiency, or lower perceived wait time for an end user (assuming there is one)? These are very different problems to solve.

Given the forum I feel obliged to point out that there some quite good coverage on these topics in Code Complete. Not C# specific mind. But that's a good thing. Bear in mind the language-specific micro-optimisations might well be subsumed into the next version of whatever compiler you're using, And if the difference between for and foreach is a big deal to you you're probably writing C++ anyway, right?

[I liked RedGate's ANTS Profiler, but I think it could be bettered]

With that out the way, some thoughts:

  • Use type(SomeType) in preference to instance.GetType() when possible
  • Use foreach in preference to for
  • Avoid boxing
  • Up to (I think) 3 strings it's ok to do StringA + StringB + StringC. After that you should use a StringBuilder

Upvotes: 11

Tim
Tim

Reputation: 20360

Profile your code. Then you can at least have an understanding of where you can improve. Without profiling you are shooting in the dark...

Upvotes: 3

Robert S.
Robert S.

Reputation: 25294

Use composition instead of inheritance, limit boxing/unboxing, use generic collections, use foreach loops instead of for{} with a counter, and release resources with the standard Dispose pattern.

These are covered in detail in the excellent book Effective C#.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499770

Unfortunately, relatively few optimisations are language specific. The basics apply across languages:

  • Measure performance against realistic loads
  • Have clearly-defined goals to guide you
  • Use a good profiler
  • Optimise architecture/design relatively early
  • Only micro-optimise when you've got a proven problem

When you've absolutely proved you need to micro-optimise, the profiler tends to make it obvious what to look for - things like avoiding boxing and virtual calls.

Oh, one thing I can think of which is .NET-specific: if you need to make a call frequently and are currently using reflection, convert those calls into delegates.

EDIT: The other answers suggesting using generics and StringBuilder etc are of course correct. I (probably wrongly) assumed that those optimisations were too "obvious" ;)

Upvotes: 13

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

In addition to the coding best practices listed above including using StringBuilders when appropriate and items of that nature.

I highly recommend using a code profiling tool such as ANTs Profiler by RedGate. I have found that after taking the standard steps for optimization that using Profiler I can further optimize my code by quickly identifying the area(s) of code that are most heavily hit by the application.

Upvotes: 0

Gary Willoughby
Gary Willoughby

Reputation: 52498

Use Ngen.exe (Should come shipped with Visual Studio.)

http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx

The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time (JIT) compiler to compile the original assembly.

Upvotes: 0

Jeff B
Jeff B

Reputation: 1866

  • Use StringBuilder rather than lots of string concatenation. String objects are atomic, and any modification (appending, to-upper, padding, etc) actually generate a completely new string object rather than modifying the original. Each new string must be allocated and eventually garbage collected.

  • A generalization of the prior statement: Try to reuse objects rather than creating lots and lots of them. Allocation and garbage collection may be easy to do, but they hit your performance.

  • Be sure to use the provided Microsoft libraries for most things. The classes provided by the Framework often use features that are unavailable or difficult to access from your own C# code (i.e. making calls out to the native Windows API). The built-in libraries are not always the most efficient, but more often than not.

  • Writing asynchronous apps has never been easier. Look into things like the BackgroundWorker class.

  • Try not to define Structs unless you really need them. Class instance variables each hold a reference to the actual instance, while struct instance variables each hold a separate copy.

Upvotes: 3

chrissie1
chrissie1

Reputation: 5029

Don't use to much reflection.

Upvotes: 0

llullulluis
llullulluis

Reputation: 3492

I recomend you those books:

Effective C#.

More Effective C#

Upvotes: 0

Ben Hoffstein
Ben Hoffstein

Reputation: 103325

One simple thing is to ensure that your build configuration is set to "Release". This will enable optimizations and eliminate debugging information, making your executable smaller.

More info on MSDN if needed.

Upvotes: 12

Konrad Rudolph
Konrad Rudolph

Reputation: 545498

Off the top of my head:

  • Replace non-generic variants of container classes by their generic counterparts
  • Cut down on boxing/unboxing. Specifically, use generics where possible and generally avoid passing value types as object.
  • For dialogs using many dynamic controls: suspend drawing until after inserting all controls by using SuspendLayout/ResumeLayout. This helps especially when using layout containers.

Upvotes: 18

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

A lot of slowness is related to database access. Make your database queries efficient and you'll do a lot for your app.

Upvotes: 3

leppie
leppie

Reputation: 117220

NGEN will help with some code, but do not bank on it.

Personally, if your design is bad/slow, there is not much you can do.

The best suggestion in such a case, is to implement some form of caching of expensive tasks.

Upvotes: 0

Related Questions