11
C# Performance ------------------------------------------------ Tips & Tricks

C# Performance Tips & Tricks .NET

Embed Size (px)

DESCRIPTION

Given the vast amount of C# and the explosive growth in data we’re dealing with, some optimisation work has been needed at various times. Most of the big gains come from really re-thinking a problem and approaching it from a whole new angle. Today however, I wanted to share some C# performance tips that have helped in my recent work. Some of these are fairly micro so don’t just charge out and employ everything here.

Citation preview

Page 1: C# Performance Tips & Tricks .NET

C# Performance

------------------------------------------------

Tips & Tricks

Page 2: C# Performance Tips & Tricks .NET

Every developer should use a Profiler

There are some great .NET profilers out there.

Our favourites are:

- dotTrace profiler from the Jet Brains team

- Red Gate profiler

Page 3: C# Performance Tips & Tricks .NET

The higher level abstraction you’re using, theslower it will often be.

LINQ is great for expressing something quicklythat might otherwise take a bunch of lines ofcode.

But in performance focused parts of your codebase you can be giving away too much. Especiallysince it’s so easy to chain together so manyoperations.

Page 4: C# Performance Tips & Tricks .NET

Don’t under estimate Release builds vs. Debug builds

I’d been doing all my tests inside Visual Studio.Release builds have optimisations enabled.

I did a release build, called the methods I wastesting from a console app.

Time for some of the micro-optimisations that the.NET JIT compiler to shine!

Page 5: C# Performance Tips & Tricks .NET

Get something running well enough in debug modeand you’re about to get some “free” performancein a release build.

- Good times!

Page 6: C# Performance Tips & Tricks .NET

Look at the bigger picture

There are some fantastic algorithms out there.

A developer doing research before coding is aboutas likely as a developer doing proper analysisbefore writing code.

We LOVE code and always want to dive right intothe IDE.

Page 7: C# Performance Tips & Tricks .NET

I recommend reading resources like CleverAlgorithms:

http://www.cleveralgorithms.com/

It was certainly an eye opener to me on some ofthe more advanced algorithms out there.

Page 8: C# Performance Tips & Tricks .NET

Lets assume we have an array of arrays.

Effectively it’s a table, 3000×3000 in size. Wewant to count how slots have a value greater thanzero in them......

Memory locality matters

Page 9: C# Performance Tips & Tricks .NET

Which of these is faster?

Page 10: C# Performance Tips & Tricks .NET

Answer? The first one.

How much so? In my tests I got about an 8xperformance improvement on this loop!

Notice the difference? It’s the order that we’rewalking this array of arrays ([i][n] vs. [n][i]).Memory locality does indeed matter in .NET eventhough we’re well abstracted from managingmemory ourselves.