SlideShare ist ein Scribd-Unternehmen logo
1 von 62
Downloaden Sie, um offline zu lesen
• Motivation
• Identifying memory traffic problems
• Specific code patterns
• General tips and tricks
• Memory allocations are cheap
• But not free
• And have side effects
• Don’t forget to think about the memory
Step I
Identification
• Provide numeric performance information about the
system
• Located in different areas in the system - disk, .NET,
networking, OS objects
• Available on-demand using built-in tools like
perfmon and typeperf
• Can write your own but that’s not the topic of our
talk…
• High-speed logging framework supporting more
than 100K structured messages per second
• .NET, drivers, services, third party components
• Can be turned on on-demand while running
• Very small overhead
• Can write your own but that’s not the topic of our
talk…
perfview
Demo
public override void Write(char value)
{
FinalText += value;
}
• Static
• Dynamic profiling
Step II
Avoidance
Searching
Demo
struct Struct {
public int Value { get; set; }
}
struct StructWithSpecializedEquals {
public int Value { get; set; }
public override bool Equals(object obj) {
if (!(obj is StructWithSpecializedEquals)) return false;
return ((StructWithSpecializedEquals)obj).Value == Value;
}
}
struct StructEquatable : IEquatable<StructEquatable> {
public int Value { get; set; }
public bool Equals(StructEquatable other) {
return Value == other.Value;
}
}
private const int N = 10000;
…
structs = Enumerable.Range(0, N)
.Select(v => new Struct { Value = v })
.ToList();
structWithSpecializedEqualses = Enumerable.Range(0, N)
.Select(v => new StructWithSpecializedEquals { Value = v })
.ToList();
structEquatables = Enumerable.Range(0, N)
.Select(v => new StructEquatable { Value = v })
.ToList();
[Benchmark]
public bool SearchStruct() {
return structs.Contains(structs.Last());
}
[Benchmark]
public bool SearchStructWithSpecializedEquals() {
…
}
[Benchmark]
public bool SearchStructEquatable() {
…
}
Capturing
Demo
public void CaptureState() {
_globalSum = 0;
for (int i = 0; i < Elements; ++i) {
var data = new Data { Value = i };
TaskStub.StartNew(() => {
_globalSum += data.Value;
});
}
}
public void PassStateAsParameter() {
_globalSum = 0;
for (int i = 0; i < Elements; ++i) {
var data = new Data { Value = i };
TaskStub.StartNew(d => {
_globalSum += (d as Data).Value;
}, data);
}
}
public void NoCapturedState() {
_globalSum = 0;
for (int i = 0; i < Elements; ++i) {
TaskStub.StartNew(() => {
_globalSum += Data.Default.Value;
});
}
}
public void NoStateAndNoLambda() {
_globalSum = 0;
for (int i = 0; i < Elements; ++i) {
TaskStub.StartNew(AddFunction);
}
}
private static void AddFunction() {
_globalSum += Data.Default.Value;
}
LINQ
Demo
public static double CalculateWithLoops() {
int sum = 0;
for (int i = Minimum; i < Maximum; ++i) {
var digits = new int[10];
var number = i;
while (number > 0) {
digits[number % 10] += 1;
number /= 10;
}
for (int d = 0; d < digits.Length; ++d)
if (digits[d] == 1) // then this is a unique digit
++sum;
}
return (double)sum / (Maximum - Minimum);
}
public static double CalculateWithLoopsAndString() {
int sum = 0;
for (int i = Minimum; i < Maximum; ++i) {
var digits = new int[10];
var s = i.ToString();
for (var k = 0; k < s.Length; ++k)
digits[s[k] - '0'] += 1;
for (int d = 0; d < digits.Length; ++d)
if (digits[d] == 1) // then this is a unique digit
++sum;
}
return (double)sum / (Maximum - Minimum);
}
public static double CalculateWithLinq() {
return Enumerable.Range(Minimum, Maximum - Minimum)
.Select(i => i.ToString()
.AsEnumerable()
.GroupBy(
c => c,
c => c,
(k, g) => new {
Character = k,
Count = g.Count()
})
.Count(g => g.Count == 1))
.Average();
}
Step III
Diligence
• You have a large heap. Don’t make it worse by
frequent calls to full GC which is going to take a long
time.
• Instead, use what we learned to reduce memory
usage
• And don’t forget to remove debugging code from
production
• Value types (structs) have a compact memory layout,
and can be embedded in their parent object, making
cache’s life easier and generally reducing footprint
• Pool expensive or large objects instead of returning
them to GC
• For large arrays (e.g. byte[]) may use
System.Buffers
• Finalizers run at some point after the object is no
longer referenced by the application (non-
deterministic)
• Finalizers run on a separate thread and create
potential concurrency issues
• Finalization prolongs object lifetime and can create
leaks if finalizers don’t complete quickly enough
• Better to use deterministic resource management
(IDisposable)
• Although a single memory allocation is extremely
fast, it adds up
• All based on real questions, stories and bugs
• Don’t overcomplicate where it’s not needed
• Measure
• And optimize…
• DIY: https://github.com/dinazil/look-mommy-no-gc
Look Mommy, No GC! (TechDays NL 2017)

Weitere ähnliche Inhalte

Was ist angesagt?

Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
SICEF
 
Open XKE - Big Data, Big Mess par Bertrand Dechoux
Open XKE - Big Data, Big Mess par Bertrand DechouxOpen XKE - Big Data, Big Mess par Bertrand Dechoux
Open XKE - Big Data, Big Mess par Bertrand Dechoux
Publicis Sapient Engineering
 
Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvas
deanhudson
 

Was ist angesagt? (20)

Java & OOP Core Concept
Java & OOP Core ConceptJava & OOP Core Concept
Java & OOP Core Concept
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
 
Declarative Infrastructure Tools
Declarative Infrastructure Tools Declarative Infrastructure Tools
Declarative Infrastructure Tools
 
The Kokkos C++ Performance Portability EcoSystem
The Kokkos C++ Performance Portability EcoSystemThe Kokkos C++ Performance Portability EcoSystem
The Kokkos C++ Performance Portability EcoSystem
 
Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)
 
Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
Webelinx - iOS development: earn 100k daily with 1h of coding #tnt3
 
Cloud jpl
Cloud jplCloud jpl
Cloud jpl
 
Kapacitor Alert Topic handlers
Kapacitor Alert Topic handlersKapacitor Alert Topic handlers
Kapacitor Alert Topic handlers
 
Open XKE - Big Data, Big Mess par Bertrand Dechoux
Open XKE - Big Data, Big Mess par Bertrand DechouxOpen XKE - Big Data, Big Mess par Bertrand Dechoux
Open XKE - Big Data, Big Mess par Bertrand Dechoux
 
Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++
 
Survey onhpcs languages
Survey onhpcs languagesSurvey onhpcs languages
Survey onhpcs languages
 
Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvas
 
TensorFlow Object Detection API
TensorFlow Object Detection APITensorFlow Object Detection API
TensorFlow Object Detection API
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
Toy Model Overview
Toy Model OverviewToy Model Overview
Toy Model Overview
 
Dma
DmaDma
Dma
 
Meet the Experts: Visualize Your Time-Stamped Data Using the React-Based Gira...
Meet the Experts: Visualize Your Time-Stamped Data Using the React-Based Gira...Meet the Experts: Visualize Your Time-Stamped Data Using the React-Based Gira...
Meet the Experts: Visualize Your Time-Stamped Data Using the React-Based Gira...
 
Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
 
Porting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUsPorting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUs
 

Ähnlich wie Look Mommy, No GC! (TechDays NL 2017)

C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 

Ähnlich wie Look Mommy, No GC! (TechDays NL 2017) (20)

Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 
Oops concept
Oops conceptOops concept
Oops concept
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
Golang in TiDB (GopherChina 2017)
Golang in TiDB  (GopherChina 2017)Golang in TiDB  (GopherChina 2017)
Golang in TiDB (GopherChina 2017)
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 

Mehr von Dina Goldshtein

Mehr von Dina Goldshtein (17)

How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)
 
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
 
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
 
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
 
Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)
 
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
 
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
 
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
 
Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)
 
Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)
 
Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
 
Things They Don’t Teach You @ School
Things They Don’t Teach You @ SchoolThings They Don’t Teach You @ School
Things They Don’t Teach You @ School
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Look Mommy, No GC! (TechDays NL 2017)

  • 1.
  • 2.
  • 3. • Motivation • Identifying memory traffic problems • Specific code patterns • General tips and tricks
  • 4. • Memory allocations are cheap • But not free • And have side effects • Don’t forget to think about the memory
  • 5.
  • 6.
  • 8. • Provide numeric performance information about the system • Located in different areas in the system - disk, .NET, networking, OS objects • Available on-demand using built-in tools like perfmon and typeperf • Can write your own but that’s not the topic of our talk…
  • 9.
  • 10. • High-speed logging framework supporting more than 100K structured messages per second • .NET, drivers, services, third party components • Can be turned on on-demand while running • Very small overhead • Can write your own but that’s not the topic of our talk…
  • 12.
  • 13.
  • 14.
  • 15. public override void Write(char value) { FinalText += value; }
  • 18.
  • 20. struct Struct { public int Value { get; set; } }
  • 21. struct StructWithSpecializedEquals { public int Value { get; set; } public override bool Equals(object obj) { if (!(obj is StructWithSpecializedEquals)) return false; return ((StructWithSpecializedEquals)obj).Value == Value; } }
  • 22. struct StructEquatable : IEquatable<StructEquatable> { public int Value { get; set; } public bool Equals(StructEquatable other) { return Value == other.Value; } }
  • 23. private const int N = 10000; … structs = Enumerable.Range(0, N) .Select(v => new Struct { Value = v }) .ToList(); structWithSpecializedEqualses = Enumerable.Range(0, N) .Select(v => new StructWithSpecializedEquals { Value = v }) .ToList(); structEquatables = Enumerable.Range(0, N) .Select(v => new StructEquatable { Value = v }) .ToList();
  • 24. [Benchmark] public bool SearchStruct() { return structs.Contains(structs.Last()); } [Benchmark] public bool SearchStructWithSpecializedEquals() { … } [Benchmark] public bool SearchStructEquatable() { … }
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 35. public void CaptureState() { _globalSum = 0; for (int i = 0; i < Elements; ++i) { var data = new Data { Value = i }; TaskStub.StartNew(() => { _globalSum += data.Value; }); } }
  • 36. public void PassStateAsParameter() { _globalSum = 0; for (int i = 0; i < Elements; ++i) { var data = new Data { Value = i }; TaskStub.StartNew(d => { _globalSum += (d as Data).Value; }, data); } }
  • 37. public void NoCapturedState() { _globalSum = 0; for (int i = 0; i < Elements; ++i) { TaskStub.StartNew(() => { _globalSum += Data.Default.Value; }); } }
  • 38. public void NoStateAndNoLambda() { _globalSum = 0; for (int i = 0; i < Elements; ++i) { TaskStub.StartNew(AddFunction); } } private static void AddFunction() { _globalSum += Data.Default.Value; }
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 47. public static double CalculateWithLoops() { int sum = 0; for (int i = Minimum; i < Maximum; ++i) { var digits = new int[10]; var number = i; while (number > 0) { digits[number % 10] += 1; number /= 10; } for (int d = 0; d < digits.Length; ++d) if (digits[d] == 1) // then this is a unique digit ++sum; } return (double)sum / (Maximum - Minimum); }
  • 48. public static double CalculateWithLoopsAndString() { int sum = 0; for (int i = Minimum; i < Maximum; ++i) { var digits = new int[10]; var s = i.ToString(); for (var k = 0; k < s.Length; ++k) digits[s[k] - '0'] += 1; for (int d = 0; d < digits.Length; ++d) if (digits[d] == 1) // then this is a unique digit ++sum; } return (double)sum / (Maximum - Minimum); }
  • 49. public static double CalculateWithLinq() { return Enumerable.Range(Minimum, Maximum - Minimum) .Select(i => i.ToString() .AsEnumerable() .GroupBy( c => c, c => c, (k, g) => new { Character = k, Count = g.Count() }) .Count(g => g.Count == 1)) .Average(); }
  • 50.
  • 52. • You have a large heap. Don’t make it worse by frequent calls to full GC which is going to take a long time. • Instead, use what we learned to reduce memory usage • And don’t forget to remove debugging code from production
  • 53.
  • 54.
  • 55.
  • 56. • Value types (structs) have a compact memory layout, and can be embedded in their parent object, making cache’s life easier and generally reducing footprint
  • 57.
  • 58. • Pool expensive or large objects instead of returning them to GC • For large arrays (e.g. byte[]) may use System.Buffers
  • 59.
  • 60. • Finalizers run at some point after the object is no longer referenced by the application (non- deterministic) • Finalizers run on a separate thread and create potential concurrency issues • Finalization prolongs object lifetime and can create leaks if finalizers don’t complete quickly enough • Better to use deterministic resource management (IDisposable)
  • 61. • Although a single memory allocation is extremely fast, it adds up • All based on real questions, stories and bugs • Don’t overcomplicate where it’s not needed • Measure • And optimize… • DIY: https://github.com/dinazil/look-mommy-no-gc