SlideShare une entreprise Scribd logo
1  sur  28
PERFORMANCE AND
BENCHMARKING
David Wengier
@ch00k
premature optimization is
the root of all evil
premature optimization is
the root of all evil
- Donald Knuth
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
“Programmers waste enormous amounts of time
thinking about, or worrying about, the speed of
noncritical parts of their programs, and these
attempts at efficiency actually have a strong negative
impact when debugging and maintenance are
considered. 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
“Programmers waste enormous amounts of time
thinking about, or worrying about, the speed of
noncritical parts of their programs, and these
attempts at efficiency actually have a strong negative
impact when debugging and maintenance are
considered. 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”,
WHEN TO OPTIMIZE?
• Optimization is fine when we know we need to
• Look at the algorithm before the code
• Micro-benchmarking is fine if the code is on the hot path
• When experience tells you some things are objectively better
• When the better performing code has other benefits
HOW TO OPTIMIZE?
• Know the context
• Question assumptions
• Release builds only
• Measure
• Measure
• Measure
HOW TO OPTIMIZE?
public static void Profile(Action func)
{
DateTime start = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
func();
}
Console.WriteLine("Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds);
}
HOW TO OPTIMIZE?
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 < 100000; i++)
{
func();
}
watch.Stop();
Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds);
}
BENCHMARKDOTNET
(not Benchmark.Net)
public class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
private string input = "1000";
[Benchmark]
public int IntParse()
{
return int.Parse(input);
}
[Benchmark]
public int ConvertToInt32()
{
return Convert.ToInt32(input);
}
}
HOW IT WORKS
• Separate process, separate run for each diagnostic.
• Pilot: The best operation count will be chosen.
• IdleWarmup, IdleTarget: Overhead will be evaluated.
• MainWarmup: Warmup of the main method.
• MainTarget: Main measurements.
• Result = MainTarget – AverageOverhead
http://benchmarkdotnet.org/HowItWorks.htm
LETS MICRO BENCHMARK!
• NO!
• Its too slow.
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
• Combining 3 x 20 character strings:
• StringBuilder: 126ns, 236 b
• Concatnation: 267ns, 213 b
• Combining 3 x 2,000,000 character strings:
• StringBuilder: 122.3 ms, 220 mb
• Concatenation: 230.9 ms, 343 mb
DICTIONARY<> VS IDICTIONARY<>
DICTIONARY<> VS IDICTIONARY<>
0 bytes allocated 32 bytes allocated
LOOPS VS LINQ
LOOPS VS LINQ
0 bytes 20 bytes 32 bytes
EXCEPTIONS VS NOT EXCEPTIONS
EXCEPTIONS VS NOT EXCEPTIONS
408 bytes 0 bytes
HYBRIDDICTIONARY
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>? 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 specify initial capacity on Lists and StringBuilders? Yes. Be nice.
SUMMARY

Contenu connexe

Similaire à Performance and Benchmarking

Ups and downs of contract testing in real life
Ups and downs of contract testing in real lifeUps and downs of contract testing in real life
Ups and downs of contract testing in real lifeOleksandr Romanov
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeGene Gotimer
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and OptimizationMongoDB
 
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairIt Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairClaire Le Goues
 
MongoDB at Baidu
MongoDB at BaiduMongoDB at Baidu
MongoDB at BaiduMat Keep
 
DockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopDockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopKevin Crawley
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prodYan Cui
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016Kim Herzig
 
DevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsDevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsTechWell
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016Peter Lawrey
 
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudUsing SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudSigOpt
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...Juan Cruz Nores
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...DataStax
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversRebecca Mills
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceESUG
 
SAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesSAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesAndrey Karpov
 
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsGo Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsJonas Bonér
 
Growing Software and Growing Ourselves
Growing Software and Growing OurselvesGrowing Software and Growing Ourselves
Growing Software and Growing OurselvesDaniel Parkin
 

Similaire à Performance and Benchmarking (20)

Ups and downs of contract testing in real life
Ups and downs of contract testing in real lifeUps and downs of contract testing in real life
Ups and downs of contract testing in real life
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy Code
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and Optimization
 
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairIt Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
 
MongoDB at Baidu
MongoDB at BaiduMongoDB at Baidu
MongoDB at Baidu
 
DockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopDockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability Workshop
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prod
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016
 
DevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsDevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More Defects
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016
 
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudUsing SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra Drivers
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
SAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesSAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilities
 
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsGo Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
 
Growing Software and Growing Ourselves
Growing Software and Growing OurselvesGrowing Software and Growing Ourselves
Growing Software and Growing Ourselves
 

Plus de David Wengier

A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019David Wengier
 
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019David Wengier
 
Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019David Wengier
 
A (brief) overview of Span<T>
A (brief) overview of Span<T>A (brief) overview of Span<T>
A (brief) overview of Span<T>David Wengier
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsDavid Wengier
 

Plus de David Wengier (6)

A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
 
Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019
 
A (brief) overview of Span<T>
A (brief) overview of Span<T>A (brief) overview of Span<T>
A (brief) overview of Span<T>
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo Skills
 

Dernier

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Dernier (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Performance and Benchmarking

  • 2. premature optimization is the root of all evil
  • 3. premature optimization is the root of all evil - Donald Knuth
  • 4. 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
  • 5. “Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. 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
  • 6. “Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. 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”,
  • 7. WHEN TO OPTIMIZE? • Optimization is fine when we know we need to • Look at the algorithm before the code • Micro-benchmarking is fine if the code is on the hot path • When experience tells you some things are objectively better • When the better performing code has other benefits
  • 8. HOW TO OPTIMIZE? • Know the context • Question assumptions • Release builds only • Measure • Measure • Measure
  • 9. HOW TO OPTIMIZE? public static void Profile(Action func) { DateTime start = DateTime.Now; for (int i = 0; i < 100000; i++) { func(); } Console.WriteLine("Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds); }
  • 10. HOW TO OPTIMIZE? 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 < 100000; i++) { func(); } watch.Stop(); Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds); }
  • 11. BENCHMARKDOTNET (not Benchmark.Net) public class Program { public static void Main(string[] args) { BenchmarkRunner.Run<Program>(); } private string input = "1000"; [Benchmark] public int IntParse() { return int.Parse(input); } [Benchmark] public int ConvertToInt32() { return Convert.ToInt32(input); } }
  • 12. HOW IT WORKS • Separate process, separate run for each diagnostic. • Pilot: The best operation count will be chosen. • IdleWarmup, IdleTarget: Overhead will be evaluated. • MainWarmup: Warmup of the main method. • MainTarget: Main measurements. • Result = MainTarget – AverageOverhead http://benchmarkdotnet.org/HowItWorks.htm
  • 13. LETS MICRO BENCHMARK! • NO! • Its too slow.
  • 14. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 15. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 16. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 17. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 18. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 19. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 20. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION • Combining 3 x 20 character strings: • StringBuilder: 126ns, 236 b • Concatnation: 267ns, 213 b • Combining 3 x 2,000,000 character strings: • StringBuilder: 122.3 ms, 220 mb • Concatenation: 230.9 ms, 343 mb
  • 22. DICTIONARY<> VS IDICTIONARY<> 0 bytes allocated 32 bytes allocated
  • 24. LOOPS VS LINQ 0 bytes 20 bytes 32 bytes
  • 25. EXCEPTIONS VS NOT EXCEPTIONS
  • 26. EXCEPTIONS VS NOT EXCEPTIONS 408 bytes 0 bytes
  • 27. HYBRIDDICTIONARY 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;
  • 28. • 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 specify initial capacity on Lists and StringBuilders? Yes. Be nice. SUMMARY

Notes de l'éditeur

  1. Heard this? Who said it?
  2. Donald Knuth. You may notice the formatting is odd.. Well, that’s because its part of a bigger quote
  3. Most people don’t know this. 97% of the time its evil, the rest its not. But why? Notice the quotes.
  4. Consider maintenance and debugging. Readability. Etc. Bonus points, what paper was it from?
  5. 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.
  6. So when do we optimize? When we should. Split the string? What about streams? StringSegments? Don’t focus on the loop Measure the hot path Pragmatism says draw on your experience Other benefits, like reusability or readability.
  7. To avoid a micro-benchmark, know the context of your data. How much? How often? Questions assumptions: “the compiler will fix this”. Will it? Release builds only! Measure
  8. DateTime is as precise as stopwatch, but not as granular Doesn’t account for JITing
  9. 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
  10. Or use BenchmarkDotNet
  11. So I’ve told you how to benchmark, and that you should basically never do it, so lets do it.
  12. Except its too slow. BenchmarkDotNet is too awesome for live demos. I have some canned ones.
  13. 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- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  14. 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- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  15. 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- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  16. 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- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  17. 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.
  18. The overhead of a class vs struct, virtual calls, etc. makes the difference. So if you use Idictionary as your parameters are you’re 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?
  19. I’m an old man so I like loops, but Linq has an overhead.
  20. Overhead in method invocations and allocations. Even the Where vs FirstOrDefault examples, because there are more iterators being allocated.
  21. 50% chance of having an invalid number. The important thing is that both benchmarks will use exactly the same input.
  22. We all know exceptions are slow, but they’re really slow. They have to collect debug information, context, stack trace etc. Don’t use for control flow.
  23. Measure! Take a leaf out of microsofts book. Know your input data. Know your context. Use the correct type.