際際滷

際際滷Share a Scribd company logo
NDC { Oslo }
2019
David Wengier
Microsoft
@davidwengier
@davidwengier
- Donald Knuth
@davidwengier
- Donald Knuth
@davidwengier
We should forget about small efficiencies, say about
97% of the time: premature optimization is the root
of all evil. Yet we should not pass up our opportunities
in that critical 3%
- Donald Knuth
@davidwengier
We should forget about small efficiencies, say about
97% of the time: premature optimization is the root
of all evil. Yet we should not pass up our opportunities
in that critical 3%
- Donald Knuth
Structured Programming with Go To Statements, 1974@davidwengier
@davidwengier
@davidwengier
@davidwengier
Dont do that, thats slow, and uses too much memory!
@davidwengier
public static void Profile(Action func)
{
DateTime start = DateTime.Now;
for (int i = 0; i < 100; i++)
{
func();
}
Console.WriteLine(Avg Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds / 100);
}
public static void Profile(Action func)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
func();
Stopwatch watch = new Stopwatch();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
watch.Start();
for (int i = 0; i < 100; i++)
{
func();
}
watch.Stop();
Console.WriteLine(Avg Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds / 100);
}
https://benchmarkdotnet.org/
https://github.com/dotnet/BenchmarkDotNet




@davidwengier






@davidwengier


@davidwengier
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
0 bytes allocated 32 bytes allocated
Pragmatic Performance from NDC Oslo 2019
0 bytes 20 bytes 32 bytes
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
public class HybridDictionary: IDictionary {
// These numbers have been carefully tested to be optimal.
// Please don't change them without doing thorough performance
// testing.
private const int CutoverPoint = 9;
 Should you always use Dictionary<K,V> instead of IDictionary<K,V>?
 Should you always use structs instead of classes?
 Should you always use for instead of foreach?
 Should you always use StringBuilder instead of concatenation?
 Should you always use traditional loops instead of Linq?
 Should you always avoid throwing exceptions?
 Should you always use Dictionary<K,V> instead of IDictionary<K,V>? No, it depends.
 Should you always use structs instead of classes? No, it depends.
 Should you always use for instead of foreach? No, it depends.
 Should you always use StringBuilder instead of concatenation? No, it depends.
 Should you always use traditional loops instead of Linq? No, it depends.
 Should you always avoid throwing exceptions? No, it depends.
 Should you always  anything? No, it probably depends.
@davidwengier
Ad

Recommended

Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019
David Wengier
JDD 2015: Artificial intelligence. Status report. - Tomasz Jackowiak
JDD 2015: Artificial intelligence. Status report. - Tomasz Jackowiak
PROIDEA
AI - Status Report
AI - Status Report
Tomasz Jackowiak
One CMS Does Not Fit All
One CMS Does Not Fit All
Rhyne Armstrong
Are You Finding True Root Causes?
Are You Finding True Root Causes?
EMMAIntl
Performance and Benchmarking
Performance and Benchmarking
David Wengier
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
Dina Goldshtein
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Fwdays
Performance is a Feature! at DDD 11
Performance is a Feature! at DDD 11
Matt Warren
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0
Richard Banks
Performance Tuning of .NET Application
Performance Tuning of .NET Application
Mainul Islam, CSM速
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Fwdays
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
LogeekNightUkraine
Refactoring to Immutability
Refactoring to Immutability
Kevlin Henney
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
Andrey Akinshin
Performance is a feature! - Developer South Coast - part 2
Performance is a feature! - Developer South Coast - part 2
Matt Warren
Performance is a Feature!
Performance is a Feature!
PostSharp Technologies
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
Fwdays
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
Dina Goldshtein
What's new in c# 8.0
What's new in c# 8.0
Moaid Hathot
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
LogeekNightUkraine
Effective c# part1
Effective c# part1
Yuriy Seniuk
.Net Framework 2 fundamentals
.Net Framework 2 fundamentals
Harshana Weerasinghe
DotNet programming & Practices
DotNet programming & Practices
Dev Raj Gautam
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
Fwdays
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
LogeekNightUkraine
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378

More Related Content

Similar to Pragmatic Performance from NDC Oslo 2019 (20)

Performance is a Feature! at DDD 11
Performance is a Feature! at DDD 11
Matt Warren
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0
Richard Banks
Performance Tuning of .NET Application
Performance Tuning of .NET Application
Mainul Islam, CSM速
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Fwdays
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
LogeekNightUkraine
Refactoring to Immutability
Refactoring to Immutability
Kevlin Henney
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
Andrey Akinshin
Performance is a feature! - Developer South Coast - part 2
Performance is a feature! - Developer South Coast - part 2
Matt Warren
Performance is a Feature!
Performance is a Feature!
PostSharp Technologies
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
Fwdays
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
Dina Goldshtein
What's new in c# 8.0
What's new in c# 8.0
Moaid Hathot
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
LogeekNightUkraine
Effective c# part1
Effective c# part1
Yuriy Seniuk
.Net Framework 2 fundamentals
.Net Framework 2 fundamentals
Harshana Weerasinghe
DotNet programming & Practices
DotNet programming & Practices
Dev Raj Gautam
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
Fwdays
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
LogeekNightUkraine
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni
Performance is a Feature! at DDD 11
Performance is a Feature! at DDD 11
Matt Warren
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0
Richard Banks
Performance Tuning of .NET Application
Performance Tuning of .NET Application
Mainul Islam, CSM速
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Fwdays
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
Kostiantyn Yelisavenko "Mastering Macro Benchmarking in .NET"
LogeekNightUkraine
Refactoring to Immutability
Refactoring to Immutability
Kevlin Henney
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
亳亰从仂仂于仆亠于亠 仂仗亳仄亳亰舒亳亳 .NET-仗亳仍仂亢亠仆亳亶
Andrey Akinshin
Performance is a feature! - Developer South Coast - part 2
Performance is a feature! - Developer South Coast - part 2
Matt Warren
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
亞仂 个亠亠仆从仂 "Direction of C# as a High-Performance Language"
Fwdays
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
Dina Goldshtein
What's new in c# 8.0
What's new in c# 8.0
Moaid Hathot
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
LogeekNightUkraine
Effective c# part1
Effective c# part1
Yuriy Seniuk
DotNet programming & Practices
DotNet programming & Practices
Dev Raj Gautam
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
"Making .NET Application Even Faster", Sergey Teplyakov.pptx
Fwdays
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
LogeekNightUkraine
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni

Recently uploaded (20)

Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
Best Software Development at Best Prices
Best Software Development at Best Prices
softechies7
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
Best Software Development at Best Prices
Best Software Development at Best Prices
softechies7
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
Ad

Pragmatic Performance from NDC Oslo 2019

  • 1. NDC { Oslo } 2019 David Wengier Microsoft @davidwengier
  • 5. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3% - Donald Knuth @davidwengier
  • 6. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3% - Donald Knuth Structured Programming with Go To Statements, 1974@davidwengier
  • 10. Dont do that, thats slow, and uses too much memory! @davidwengier
  • 11. public static void Profile(Action func) { DateTime start = DateTime.Now; for (int i = 0; i < 100; i++) { func(); } Console.WriteLine(Avg Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds / 100); }
  • 12. public static void Profile(Action func) { Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; Thread.CurrentThread.Priority = ThreadPriority.Highest; func(); Stopwatch watch = new Stopwatch(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); watch.Start(); for (int i = 0; i < 100; i++) { func(); } watch.Stop(); Console.WriteLine(Avg Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds / 100); }
  • 19.
  • 21. 0 bytes allocated 32 bytes allocated
  • 22.
  • 24. 0 bytes 20 bytes 32 bytes
  • 25.
  • 28.
  • 29. public class HybridDictionary: IDictionary { // These numbers have been carefully tested to be optimal. // Please don't change them without doing thorough performance // testing. private const int CutoverPoint = 9;
  • 30. Should you always use Dictionary<K,V> instead of IDictionary<K,V>? Should you always use structs instead of classes? Should you always use for instead of foreach? Should you always use StringBuilder instead of concatenation? Should you always use traditional loops instead of Linq? Should you always avoid throwing exceptions?
  • 31. Should you always use Dictionary<K,V> instead of IDictionary<K,V>? No, it depends. Should you always use structs instead of classes? No, it depends. Should you always use for instead of foreach? No, it depends. Should you always use StringBuilder instead of concatenation? No, it depends. Should you always use traditional loops instead of Linq? No, it depends. Should you always avoid throwing exceptions? No, it depends. Should you always anything? No, it probably depends.

Editor's Notes

  • #3: Whos heard this? This gets carted out on PRs, and usually as a negative. Either someone changes a linq statement to foreach statement, and someone else says dont bother, premature opt. Or someone writes a linq statement, someone comments saying it should be a foreach statement, and then in order to be lazy, premature opt.. But first, Who said it?
  • #4: Donald Knuth. K-nooth. You may notice the formatting is odd.. Well, thats because its part of a bigger quote
  • #5: Most people dont know this. 97% of the time its evil, the rest its not. But why? Notice the quotes.
  • #6: Consider maintenance and debugging. Readability. Etc. Bonus points, what paper was it from?
  • #7: Ironically, a quote that lots of developers spout as being gospel comes from a paper arguing that programming with go to statements is perfectly fine. A debate for another time.
  • #8: How much? How often?
  • #9: Questions assumptions: the compiler will fix this. Will it? Release builds only!
  • #10: Measure. Before and After.
  • #12: DateTime is as precise as stopwatch, but not as granular Doesnt account for JITing
  • #13: High affinity, so nothing else on the machine matters (hopefully) JIT first Get GC out of the way, because GC pauses are bad for benchmarking Then go
  • #14: Or use BenchmarkDotNet
  • #15: So Ive told you how to benchmark, and that you should basically never do it, so lets do it.
  • #16: Except its too slow. Its _thorough_ BenchmarkDotNet is too awesome for live demos. I have some canned ones.
  • #19: Concat wins Then stringbuilder StringBuilder again Now StringBuilder with capacity, and that trend continues forever If we add more, we can see stringbuilder and string join are both a lot fast As we keep going, the difference gets bigger Looks like a slam dunk right? Always use a string builder with capacity? BUT- dont forget context!!! Look what happens as the strings get longer. Now it doesnt matter so much, as long as you dont concatenate
  • #20: Back to context, again production code.. For 3 small strings, concatenation is slower, but not measurably so. But it uses less memory. The overhead of StringBuilder might make it a winner. For large strings, not so. Stopwatch granularity is around 300ns, so the difference in the first one is effectively unmeasurable in production .NET code. For large strings SB still uses heaps of memory. Are strings the best thing to use at all? Step back
  • #22: The overhead of a class vs struct, virtual calls, etc. makes the difference. So if you use Idictionary as your parameters are youre supposed to do, on a hot path that might be a negative. Question assumptions.. How many of you think coding to interfaces is _always_ better?
  • #24: Im an old man so I like loops, but Linq has an overhead.
  • #25: Overhead in method invocations and allocations. Even the Where vs FirstOrDefault examples, because there are more iterators being allocated. Where uses an iterator, FirstOrDefault uses a foreach loop
  • #27: 50% chance of having an invalid number. The important thing is that both benchmarks will use exactly the same input.
  • #29: Question assumptions!
  • #30: Culture of performance means measure, not necessarily write complicated code
  • #32: Pragmatic. Every decision is unique. Dont write off performance, but dont write off anything.