Optimizing C# Code
Line-by-line, Part I
Chris B. Behrens
@chrisbbehrens
The Practice of Performance
Skip the stuff you’re sure you
Habit installation
already know
An Important Principle That
BenchmarkDotNet Teaches Us
It executes the function Otherwise, short-term resource
over and over again volatility can swamp the measure
You should care one
thousand times as much
about code that gets
executed one thousand
times as often
Pure Compute Functions
Azure functions Functions which will You are literally billed
be executed often for performance
Pareto Analysis for Optimization
This applies often in
80/20
surprising ways
80% of the poor
performance of your
application comes from 20%
of the code
Half-split Your Way to Optimized Code
Application
Half 1 > Half 2
Half 1 > Half 2
Half 1 < Half 2 Poorly performing core function
Up Next:
Let’s Get Started
Demo Our BuildStringBadly function
Unroll it a little bit so that we can
understand it
Why BuildStringBetter is performing better
What habit we can install
Why Not Just Make
Strings Mutable?
This would make Changing a value
This is unlikely to
everything else type to a reference
change
worse type
One Last Point
We’re not going to The further you optimize, the
optimize fully more you trade -ilities
Demo Look at a very common string problem
Look at the naïve way to work with it
Look at a slightly more intuitive way to
work with it
Learn a new-ish way to work with strings
An ounce of test is worth a
pound of guess
Test as Soon as You Can
I was surprised That’s the point
Demo Compare string
Using the equality operator
Using string.Equals
Using string.Compare
Look at one of the options
An ounce of test is worth a
pound of guess
Demo
For loops
Foreach
Look at them in several different scenarios
Extract a general principle
Performance tips on the
Internet are not versioned
.NET Changes over Time
And things that are different
Stuff gets optimized under
in code end up the same in
the covers
the IL
Demo
Classes
Structs
Compare the two
How records fit into this
Key aspects in choosing between structs and
classes
https://bit.ly/3hdOCi5
1. It logically represents a single value, similar
to primitive types (int, double, etc.)
2. It has an instance size under 16 bytes
3. It is immutable
4. It will not have to be boxed frequently
Boxing and Unboxing
Boxing Unboxing
int year = 2112;
int year = (int)o;
object o = year;
Mutability comes with a
price