SlideShare a Scribd company logo
State of the
.NET Performance
Adam Sitnik
About myself
Work:
• Energy trading (.NET Core)
• Energy Production Optimization
• Balance Settlement
• Critical Events Detection
Open Source:
• BenchmarkDotNet (.NET Core)
• Core CLR (Spans)
• corefxlab (optimizations)
• & more
2
Agenda
• C# 7
• ValueTuple
• ref returns and locals
• .NET Core
• Span (Slice)
• ArrayPool
• ValueTask
• Pipelines (Channels)
• Unsafe
• Supported frameworks
• Questions
3
ValueTuple: sample
4
(double min, double max, double avg, double sum) GetStats(double[] numbers)
{
double min = double.MaxValue, max = double.MinValue, sum = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > max) max = numbers[i];
if (numbers[i] < min) min = numbers[i];
sum += numbers[i];
}
double avg = numbers.Length != 0 ? sum / numbers.Length : double.NaN;
return (min, max, avg, sum);
}
ValueTuple
5
• Tuple which is Value Type:
• less space
• better data locality
• NO GC
• deterministic deallocation for stack-allocated Value Types
You need reference to System.ValueTuple.dll
Value Types: the disadvantages?!
• Are expensive to copy!
• You need to study CIL and profiles to find out when it happens!
int result = readOnlyStructField.Method();
is converted to:
var copy = readOnlyStruct;
int result = copy.Method();
6
ref returns and locals: sample
7
ref int Max(
ref int first, ref int second, ref int third)
{
ref int max = ref first;
if (first < second) max = second;
if (second < third) max = third;
return ref max;
}
ref locals: Benchmarks: initialization
public void ByValue() {
for (int i = 0; i < array.Length; i++) {
BigStruct value = array[i];
value.Int1 = 1;
value.Int2 = 2;
value.Int3 = 3;
value.Int4 = 4;
value.Int5 = 5;
array[i] = value;
}
}
public void ByReference(){
for (int i = 0; i < array.Length; i++) {
ref BigStruct reference = ref array[i];
reference.Int1 = 1;
reference.Int2 = 2;
reference.Int3 = 3;
reference.Int4 = 4;
reference.Int5 = 5;
}
}
8
struct BigStruct { public int Int1, Int2, Int3, Int4, Int5; }
Benchmark
results
9
How can old JITs
support it?
What about unsafe?!
void ByReferenceUnsafeExplicitExtraMethod()
{
unsafe
{
fixed (BigStruct* pinned = array)
{
for (int i = 0;
i < array.Length; i++)
{
Init(&pinned[i]);
}
}
}
}
unsafe void Init(BigStruct* pointer)
{
(*pointer).Int1 = 1;
(*pointer).Int2 = 2;
(*pointer).Int3 = 3;
(*pointer).Int4 = 4;
(*pointer).Int5 = 5;
}
10
Safe vs Unsafe with RyuJit
Method Jit Mean Scaled
ByValue RyuJit 742.4910 ns 4.56
ByReference RyuJit 162.8368 ns 1.00
ByReferenceOldWay RyuJit 170.0255 ns 1.04
ByReferenceUnsafeImplicit RyuJit 201.4584 ns 1.24
ByReferenceUnsafeExplicit RyuJit 200.7698 ns 1.23
ByReferenceUnsafeExplicitExtraMethod RyuJit 171.3973 ns 1.05
11
Executing Unsafe code requires full trust. It can be a „no go” for Cloud!
No need for pinning!
Stackalloc is
the fastest
way to
allocate small
chunks of
memory in
.NET
12
13
Allocation Deallocation Usage
Managed < 85 KB Very cheap
(NextObjPtr)
• non-deterministic
• Expensive!
• GC: stop the world • Very easy
• Common
• Safe
Managed: LOH Acceptable cost
(free list
management)
The same as above &:
• Fragmentation (LOH)
• LOH = Gen 2 = Full GC
Native:
Stackalloc
Very cheap • Deterministic
• Very cheap • Unsafe
• Not
common
• Limited
Native: Marshal Acceptable cost
(free list
management)
• Deterministic
• Very cheap
• On demand
Span (Slice)
It provides a uniform API for working with:
• Unmanaged memory buffers
• Arrays and subarrays
• Strings and substrings
It’s fully type-safe and memory-safe.
Almost no overhead.
It’s a Value Type.
15
Supports any memory
byte* pointerToStack = stackalloc byte[256];
Span<byte> stackMemory = new Span<byte>(pointerToStack, 256);
Span<byte> stackMemory = stackalloc byte[256]; // C# 8.0?
IntPtr unmanagedHandle = Marshal.AllocHGlobal(256);
Span<byte> unmanaged = new Span<byte>(unmanagedHandle.ToPointer(), 256);
Span<byte> unmanaged = Marshal.AllocHGlobal(256); // C# 8.0?
char[] array = new char[] { 'D', 'O', 'T', ' ', 'N', 'E', 'X', 'T' };
Span<char> fromArray = new Span<char>(array);
16
Single method in the API is enough
unsafe void Handle(byte* buffer, int length) { }
void Handle(byte[] buffer) { }
void Handle(Span<T> buffer) { }
17
Uniform access to any kind of contiguous memory
public void Enumeration<T>(Span<T> buffer)
{
for (int i = 0; i < buffer.Length; i++)
{
Use(buffer[i]);
}
foreach (T item in buffer)
{
Use(item);
}
}
18
Span for new runtimes
• CoreCLR 1.2
• CLR 4.6.3? 4.6.4?
19
Span for existing runtimes
20
.NET 4.5+, .NET Standard 1.0
Make subslices without allocations
ReadOnlySpan<char> subslice =
".NET Core: Performance Storm!"
.Slice(start: 0, length: 9);
21
22
Subslice
benchmarks
Possible usages
• Formatting
• Base64/Unicode encoding
• HTTP Parsing/Writing
• Compression/Decompression
• XML/JSON parsing/writing
• Binary reading/writing
• & more!!
23
GC Pauses
24
.NET Managed Heap*
25
G
e
n
0
G
e
n
1
Gen 2 LOH
* - simplified, Workstation mode or view per logical processor in Server mode
FULL GC
ArrayPool
• System.Buffers package
• Provides a resource pool that enables reusing instances of T[]
• Arrays allocated on managed heap with new operator
• The default maximum length of each array in the pool is 2^20
(1024*1024 = 1 048 576)
26
ArrayPool: Sample
var pool = ArrayPool<byte>.Shared;
byte[] buffer = pool.Rent(minLength);
try
{
Use(buffer);
}
finally
{
pool.Return(buffer);
}
27
10 KB
29
1 MB
30
1 MB
31
Method Median StdDev Scaled Delta Gen 0 Gen 1 Gen 2
stackalloc 51,689.8611 ns 3,343.26 ns 3.76 275.9% - - -
New 13,750.9839 ns 974.0229 ns 1.00 Baseline - - 23 935
NativePool.Shared 186.1173 ns 12.6833 ns 0.01 -98.6% - - -
ArrayPool.Shared 61.4539 ns 3.4862 ns 0.00 -99.6% - - -
SizeAware 54.5332 ns 2.1022 ns 0.00 -99.6% - - -
32
10 MB
Async on hotpath
Task<T> SmallMethodExecutedVeryVeryOften()
{
if(CanRunSynchronously()) // true most of the time
{
return Task.FromResult(ExecuteSynchronous());
}
return ExecuteAsync();
}
33
Async on hotpath: consuming method
while (true)
{
var result = await SmallMethodExecutedVeryVeryOften();
Use(result);
}
34
ValueTask<T>: the idea
• Wraps a TResult and Task<TResult>, only one of which is used
• It should not replace Task, but help in some scenarios when:
• method returns Task<TResult>
• and very frequently returns synchronously (fast)
• and is invoked so often that cost of allocation of
Task<TResult> is a problem
37
Sample implementation of ValueTask usage
ValueTask<T> SampleUsage()
{
if (IsFastSynchronousExecutionPossible())
{
return ExecuteSynchronous(); // INLINEABLE!!!
}
return new ValueTask<T>(ExecuteAsync());
}
T ExecuteSynchronous() { }
Task<T> ExecuteAsync() { }
38
How to consume ValueTask
var valueTask = SampleUsage(); // INLINEABLE
if(valueTask.IsCompleted)
{
Use(valueTask.Result);
}
else
{
Use(await valueTask.AsTask()); // NO INLINING
}
39
ValueTask<T>: usage && gains
• Sample usage:
• Sockets (already used in ASP.NET Core)
• File Streams
• ADO.NET Data readers
• Gains:
• Less heap allocations
• Method inlining is possible!
• Facts
• Skynet 146ns for Task, 16ns for ValueTask
• Tech Empower (Plaintext) +2.6%
40
ValueTask
vs
Task:
Creation
41
Web Request
42
Pipelines (Channels)
• „ high performance zero-copy buffer-pool-managed asynchronous message
pipes” – Marc Gravell from Stack Overflow
• Pipeline pushes data to you rather than having you pull.
• When writing to a pipeline, the caller allocates memory from the pipeline
directly.
• No new memory is allocated. Only pooled memory buffer is used.
43
Simplified Flow
Asks for a memory buffer.
Writes the data to the buffer.
Returns pooled memory.
Starts awaiting for the data.
Reads the data from buffer.
Uses low-allocating Span based
apis (parsing etc).
Returns the memory to the pool
when done.
44
System.Runtime.CompilerServices.Unsafe
T As<T>(object o) where T : class;
void* AsPointer<T>(ref T value);
void Copy<T>(void* destination, ref T source);
void Copy<T>(ref T destination, void* source);
void CopyBlock(void* destination, void* source, uint byteCount);
void InitBlock(void* startAddress, byte value, uint byteCount);
T Read<T>(void* source);
int SizeOf<T>();
void Write<T>(void* destination, T value);
45
Supported frameworks
46
Package name .NET
Standard
.NET
Framework
Release Nuget feed
System.Slices 1.0 4.5 1.2? Clr/fxlab
System.Buffers 1.1 4.5.1 1.0 nuget.org
System.Threading.Task.Extensions 1.0 4.5 1.0 nuget.org
System.Runtime.CompilerServices.Unsafe 1.0 4.5 1.0 corefx
Questions?
Contact:
@SitnikAdam
Adam.Sitnik@gmail.com
You can find the benchmarks at
https://github.com/adamsitnik/DotNetCorePerformance
https://github.com/adamsitnik/CSharpSevenBenchmarks

More Related Content

What's hot

Конверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемыеКонверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемые
Platonov Sergey
 
Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexes
Daniel Lemire
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
Max Kleiner
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
Computer Science Club
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
Computer Science Club
 
Arduino C maXbox web of things slide show
Arduino C maXbox web of things slide showArduino C maXbox web of things slide show
Arduino C maXbox web of things slide show
Max Kleiner
 
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"
Yulia Tsisyk
 
Porting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUsPorting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUs
Igor Sfiligoi
 
Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic Languages
Tobias Lindaaker
 
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from..."PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
Edge AI and Vision Alliance
 
Lec09 nbody-optimization
Lec09 nbody-optimizationLec09 nbody-optimization
Lec09 nbody-optimization
Taras Zakharchenko
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
Andrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
PVS-Studio
 
Lec05 buffers basic_examples
Lec05 buffers basic_examplesLec05 buffers basic_examples
Lec05 buffers basic_examples
Taras Zakharchenko
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torch
Riza Fahmi
 
Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33
Max Kleiner
 
C++ & Java JIT Optimizations: Finding Prime Numbers
C++ & Java JIT Optimizations: Finding Prime NumbersC++ & Java JIT Optimizations: Finding Prime Numbers
C++ & Java JIT Optimizations: Finding Prime Numbers
Adam Feldscher
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
Andrey Karpov
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
Jules Krdenas
 

What's hot (20)

Конверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемыеКонверсия управляемых языков в неуправляемые
Конверсия управляемых языков в неуправляемые
 
Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexes
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
Arduino C maXbox web of things slide show
Arduino C maXbox web of things slide showArduino C maXbox web of things slide show
Arduino C maXbox web of things slide show
 
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"
 
Porting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUsPorting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUs
 
Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic Languages
 
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from..."PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
 
Lec09 nbody-optimization
Lec09 nbody-optimizationLec09 nbody-optimization
Lec09 nbody-optimization
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Lec05 buffers basic_examples
Lec05 buffers basic_examplesLec05 buffers basic_examples
Lec05 buffers basic_examples
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torch
 
Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33
 
C++ & Java JIT Optimizations: Finding Prime Numbers
C++ & Java JIT Optimizations: Finding Prime NumbersC++ & Java JIT Optimizations: Finding Prime Numbers
C++ & Java JIT Optimizations: Finding Prime Numbers
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
 

Viewers also liked

Опыт построения микросервисной архитектуры в цифровом банке
Опыт построения микросервисной архитектуры в цифровом банкеОпыт построения микросервисной архитектуры в цифровом банке
Опыт построения микросервисной архитектуры в цифровом банке
CUSTIS
 
Agile и управление знаниями в ИТ-проектах
Agile и управление знаниями в ИТ-проектахAgile и управление знаниями в ИТ-проектах
Agile и управление знаниями в ИТ-проектах
CUSTIS
 
Золотая лихорадка MSA: почему нам не подошли микросервисы?
Золотая лихорадка MSA: почему нам не подошли микросервисы?Золотая лихорадка MSA: почему нам не подошли микросервисы?
Золотая лихорадка MSA: почему нам не подошли микросервисы?
CUSTIS
 
Три истории микросервисов
Три истории микросервисовТри истории микросервисов
Три истории микросервисов
CUSTIS
 
Будущее omni-channel маркетинга: инструменты, кейсы и цифры
Будущее omni-channel маркетинга: инструменты, кейсы и цифрыБудущее omni-channel маркетинга: инструменты, кейсы и цифры
Будущее omni-channel маркетинга: инструменты, кейсы и цифры
CUSTIS
 
Барьеры микросервисной архитектуры
Барьеры микросервисной архитектурыБарьеры микросервисной архитектуры
Барьеры микросервисной архитектуры
CUSTIS
 

Viewers also liked (6)

Опыт построения микросервисной архитектуры в цифровом банке
Опыт построения микросервисной архитектуры в цифровом банкеОпыт построения микросервисной архитектуры в цифровом банке
Опыт построения микросервисной архитектуры в цифровом банке
 
Agile и управление знаниями в ИТ-проектах
Agile и управление знаниями в ИТ-проектахAgile и управление знаниями в ИТ-проектах
Agile и управление знаниями в ИТ-проектах
 
Золотая лихорадка MSA: почему нам не подошли микросервисы?
Золотая лихорадка MSA: почему нам не подошли микросервисы?Золотая лихорадка MSA: почему нам не подошли микросервисы?
Золотая лихорадка MSA: почему нам не подошли микросервисы?
 
Три истории микросервисов
Три истории микросервисовТри истории микросервисов
Три истории микросервисов
 
Будущее omni-channel маркетинга: инструменты, кейсы и цифры
Будущее omni-channel маркетинга: инструменты, кейсы и цифрыБудущее omni-channel маркетинга: инструменты, кейсы и цифры
Будущее omni-channel маркетинга: инструменты, кейсы и цифры
 
Барьеры микросервисной архитектуры
Барьеры микросервисной архитектурыБарьеры микросервисной архитектуры
Барьеры микросервисной архитектуры
 

Similar to State of the .Net Performance

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
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
Christian Nagel
 
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-OptimisationsWhere the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
 
"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
Fwdays
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
Dina Goldshtein
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
Ynon Perek
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
Brendan Gregg
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
Cyber Security Alliance
 
Fedor Polyakov - Optimizing computer vision problems on mobile platforms
Fedor Polyakov - Optimizing computer vision problems on mobile platforms Fedor Polyakov - Optimizing computer vision problems on mobile platforms
Fedor Polyakov - Optimizing computer vision problems on mobile platforms
Eastern European Computer Vision Conference
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
Christian Nagel
 
Kapacitor - Real Time Data Processing Engine
Kapacitor - Real Time Data Processing EngineKapacitor - Real Time Data Processing Engine
Kapacitor - Real Time Data Processing Engine
Prashant Vats
 
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovWorkshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Fwdays
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
Võ Hòa
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
Richárd Kovács
 
Tamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptxTamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Tools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in AndroidTools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
Golang in TiDB (GopherChina 2017)
Golang in TiDB  (GopherChina 2017)Golang in TiDB  (GopherChina 2017)
Golang in TiDB (GopherChina 2017)
PingCAP
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
Dawid Rusnak
 

Similar to State of the .Net Performance (20)

A (brief) overview of Span<T>
A (brief) overview of Span<T>A (brief) overview of Span<T>
A (brief) overview of Span<T>
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-OptimisationsWhere the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
 
"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
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
 
Fedor Polyakov - Optimizing computer vision problems on mobile platforms
Fedor Polyakov - Optimizing computer vision problems on mobile platforms Fedor Polyakov - Optimizing computer vision problems on mobile platforms
Fedor Polyakov - Optimizing computer vision problems on mobile platforms
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
 
Kapacitor - Real Time Data Processing Engine
Kapacitor - Real Time Data Processing EngineKapacitor - Real Time Data Processing Engine
Kapacitor - Real Time Data Processing Engine
 
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovWorkshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Tamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptxTamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptx
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
Tools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in AndroidTools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in Android
 
Golang in TiDB (GopherChina 2017)
Golang in TiDB  (GopherChina 2017)Golang in TiDB  (GopherChina 2017)
Golang in TiDB (GopherChina 2017)
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
 

More from CUSTIS

Три истории микросервисов, или MSA для Enterprise
Три истории микросервисов, или MSA для EnterpriseТри истории микросервисов, или MSA для Enterprise
Три истории микросервисов, или MSA для Enterprise
CUSTIS
 
Долгоживущие ИТ в динамичном ритейле
Долгоживущие ИТ в динамичном ритейлеДолгоживущие ИТ в динамичном ритейле
Долгоживущие ИТ в динамичном ритейле
CUSTIS
 
Будущее уже наступило: от Agile к бирюзовым организациям
Будущее уже наступило: от Agile к бирюзовым организациямБудущее уже наступило: от Agile к бирюзовым организациям
Будущее уже наступило: от Agile к бирюзовым организациям
CUSTIS
 
Как выбрать для проекта практики проектирования и работы с требованиями
Как выбрать для проекта практики проектирования и работы с требованиямиКак выбрать для проекта практики проектирования и работы с требованиями
Как выбрать для проекта практики проектирования и работы с требованиями
CUSTIS
 
Диаграммы учета как средство для наглядного и целостного отображения правил у...
Диаграммы учета как средство для наглядного и целостного отображения правил у...Диаграммы учета как средство для наглядного и целостного отображения правил у...
Диаграммы учета как средство для наглядного и целостного отображения правил у...
CUSTIS
 
Сотрудничество с корпорациями: рецепты из практики
Сотрудничество с корпорациями: рецепты из практикиСотрудничество с корпорациями: рецепты из практики
Сотрудничество с корпорациями: рецепты из практики
CUSTIS
 
Agile — ответ на вызовы третьей промышленной революции
Agile — ответ на вызовы третьей промышленной революцииAgile — ответ на вызовы третьей промышленной революции
Agile — ответ на вызовы третьей промышленной революции
CUSTIS
 
От монолитных моделей предметной области — к модульным
От монолитных моделей предметной области — к модульнымОт монолитных моделей предметной области — к модульным
От монолитных моделей предметной области — к модульным
CUSTIS
 
Проблемы управления правами доступа к информационным системам крупной торгово...
Проблемы управления правами доступа к информационным системам крупной торгово...Проблемы управления правами доступа к информационным системам крупной торгово...
Проблемы управления правами доступа к информационным системам крупной торгово...
CUSTIS
 
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделять
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделятьОтветственность за качество в разных ИТ-проектах: в чем она и как ее разделять
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделять
CUSTIS
 
Опыт применения метода ATAM для оценки архитектуры
Опыт применения метода ATAM для оценки архитектурыОпыт применения метода ATAM для оценки архитектуры
Опыт применения метода ATAM для оценки архитектуры
CUSTIS
 
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватает
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватаетГибридный подход к управлению правами доступа: когда стандартного IDM не хватает
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватает
CUSTIS
 
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
CUSTIS
 
Process и Case Management в информационной системе: от автоматизации As Is к ...
Process и Case Management в информационной системе: от автоматизации As Is к ...Process и Case Management в информационной системе: от автоматизации As Is к ...
Process и Case Management в информационной системе: от автоматизации As Is к ...
CUSTIS
 
RBAC & ABAC: гибридное решение для управления правами доступа
RBAC & ABAC: гибридное решение для управления правами доступаRBAC & ABAC: гибридное решение для управления правами доступа
RBAC & ABAC: гибридное решение для управления правами доступа
CUSTIS
 
Омниканальная модель в ритейле: решения и кейсы
Омниканальная модель в ритейле: решения и кейсыОмниканальная модель в ритейле: решения и кейсы
Омниканальная модель в ритейле: решения и кейсы
CUSTIS
 
WinDbg со товарищи
WinDbg со товарищиWinDbg со товарищи
WinDbg со товарищи
CUSTIS
 
Akka.NET
Akka.NETAkka.NET
Akka.NET
CUSTIS
 
Process & Case Management: совмещай и властвуй!
Process & Case Management: совмещай и властвуй!Process & Case Management: совмещай и властвуй!
Process & Case Management: совмещай и властвуй!
CUSTIS
 
Программы лояльности в эпоху omni
Программы лояльности в эпоху omniПрограммы лояльности в эпоху omni
Программы лояльности в эпоху omni
CUSTIS
 

More from CUSTIS (20)

Три истории микросервисов, или MSA для Enterprise
Три истории микросервисов, или MSA для EnterpriseТри истории микросервисов, или MSA для Enterprise
Три истории микросервисов, или MSA для Enterprise
 
Долгоживущие ИТ в динамичном ритейле
Долгоживущие ИТ в динамичном ритейлеДолгоживущие ИТ в динамичном ритейле
Долгоживущие ИТ в динамичном ритейле
 
Будущее уже наступило: от Agile к бирюзовым организациям
Будущее уже наступило: от Agile к бирюзовым организациямБудущее уже наступило: от Agile к бирюзовым организациям
Будущее уже наступило: от Agile к бирюзовым организациям
 
Как выбрать для проекта практики проектирования и работы с требованиями
Как выбрать для проекта практики проектирования и работы с требованиямиКак выбрать для проекта практики проектирования и работы с требованиями
Как выбрать для проекта практики проектирования и работы с требованиями
 
Диаграммы учета как средство для наглядного и целостного отображения правил у...
Диаграммы учета как средство для наглядного и целостного отображения правил у...Диаграммы учета как средство для наглядного и целостного отображения правил у...
Диаграммы учета как средство для наглядного и целостного отображения правил у...
 
Сотрудничество с корпорациями: рецепты из практики
Сотрудничество с корпорациями: рецепты из практикиСотрудничество с корпорациями: рецепты из практики
Сотрудничество с корпорациями: рецепты из практики
 
Agile — ответ на вызовы третьей промышленной революции
Agile — ответ на вызовы третьей промышленной революцииAgile — ответ на вызовы третьей промышленной революции
Agile — ответ на вызовы третьей промышленной революции
 
От монолитных моделей предметной области — к модульным
От монолитных моделей предметной области — к модульнымОт монолитных моделей предметной области — к модульным
От монолитных моделей предметной области — к модульным
 
Проблемы управления правами доступа к информационным системам крупной торгово...
Проблемы управления правами доступа к информационным системам крупной торгово...Проблемы управления правами доступа к информационным системам крупной торгово...
Проблемы управления правами доступа к информационным системам крупной торгово...
 
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделять
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделятьОтветственность за качество в разных ИТ-проектах: в чем она и как ее разделять
Ответственность за качество в разных ИТ-проектах: в чем она и как ее разделять
 
Опыт применения метода ATAM для оценки архитектуры
Опыт применения метода ATAM для оценки архитектурыОпыт применения метода ATAM для оценки архитектуры
Опыт применения метода ATAM для оценки архитектуры
 
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватает
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватаетГибридный подход к управлению правами доступа: когда стандартного IDM не хватает
Гибридный подход к управлению правами доступа: когда стандартного IDM не хватает
 
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
Собираем кубик Рубика: восстановление архитектурного описания корпоративной р...
 
Process и Case Management в информационной системе: от автоматизации As Is к ...
Process и Case Management в информационной системе: от автоматизации As Is к ...Process и Case Management в информационной системе: от автоматизации As Is к ...
Process и Case Management в информационной системе: от автоматизации As Is к ...
 
RBAC & ABAC: гибридное решение для управления правами доступа
RBAC & ABAC: гибридное решение для управления правами доступаRBAC & ABAC: гибридное решение для управления правами доступа
RBAC & ABAC: гибридное решение для управления правами доступа
 
Омниканальная модель в ритейле: решения и кейсы
Омниканальная модель в ритейле: решения и кейсыОмниканальная модель в ритейле: решения и кейсы
Омниканальная модель в ритейле: решения и кейсы
 
WinDbg со товарищи
WinDbg со товарищиWinDbg со товарищи
WinDbg со товарищи
 
Akka.NET
Akka.NETAkka.NET
Akka.NET
 
Process & Case Management: совмещай и властвуй!
Process & Case Management: совмещай и властвуй!Process & Case Management: совмещай и властвуй!
Process & Case Management: совмещай и властвуй!
 
Программы лояльности в эпоху omni
Программы лояльности в эпоху omniПрограммы лояльности в эпоху omni
Программы лояльности в эпоху omni
 

Recently uploaded

Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 

Recently uploaded (20)

Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 

State of the .Net Performance

  • 1. State of the .NET Performance Adam Sitnik
  • 2. About myself Work: • Energy trading (.NET Core) • Energy Production Optimization • Balance Settlement • Critical Events Detection Open Source: • BenchmarkDotNet (.NET Core) • Core CLR (Spans) • corefxlab (optimizations) • & more 2
  • 3. Agenda • C# 7 • ValueTuple • ref returns and locals • .NET Core • Span (Slice) • ArrayPool • ValueTask • Pipelines (Channels) • Unsafe • Supported frameworks • Questions 3
  • 4. ValueTuple: sample 4 (double min, double max, double avg, double sum) GetStats(double[] numbers) { double min = double.MaxValue, max = double.MinValue, sum = 0; for (int i = 0; i < numbers.Length; i++) { if (numbers[i] > max) max = numbers[i]; if (numbers[i] < min) min = numbers[i]; sum += numbers[i]; } double avg = numbers.Length != 0 ? sum / numbers.Length : double.NaN; return (min, max, avg, sum); }
  • 5. ValueTuple 5 • Tuple which is Value Type: • less space • better data locality • NO GC • deterministic deallocation for stack-allocated Value Types You need reference to System.ValueTuple.dll
  • 6. Value Types: the disadvantages?! • Are expensive to copy! • You need to study CIL and profiles to find out when it happens! int result = readOnlyStructField.Method(); is converted to: var copy = readOnlyStruct; int result = copy.Method(); 6
  • 7. ref returns and locals: sample 7 ref int Max( ref int first, ref int second, ref int third) { ref int max = ref first; if (first < second) max = second; if (second < third) max = third; return ref max; }
  • 8. ref locals: Benchmarks: initialization public void ByValue() { for (int i = 0; i < array.Length; i++) { BigStruct value = array[i]; value.Int1 = 1; value.Int2 = 2; value.Int3 = 3; value.Int4 = 4; value.Int5 = 5; array[i] = value; } } public void ByReference(){ for (int i = 0; i < array.Length; i++) { ref BigStruct reference = ref array[i]; reference.Int1 = 1; reference.Int2 = 2; reference.Int3 = 3; reference.Int4 = 4; reference.Int5 = 5; } } 8 struct BigStruct { public int Int1, Int2, Int3, Int4, Int5; }
  • 10. What about unsafe?! void ByReferenceUnsafeExplicitExtraMethod() { unsafe { fixed (BigStruct* pinned = array) { for (int i = 0; i < array.Length; i++) { Init(&pinned[i]); } } } } unsafe void Init(BigStruct* pointer) { (*pointer).Int1 = 1; (*pointer).Int2 = 2; (*pointer).Int3 = 3; (*pointer).Int4 = 4; (*pointer).Int5 = 5; } 10
  • 11. Safe vs Unsafe with RyuJit Method Jit Mean Scaled ByValue RyuJit 742.4910 ns 4.56 ByReference RyuJit 162.8368 ns 1.00 ByReferenceOldWay RyuJit 170.0255 ns 1.04 ByReferenceUnsafeImplicit RyuJit 201.4584 ns 1.24 ByReferenceUnsafeExplicit RyuJit 200.7698 ns 1.23 ByReferenceUnsafeExplicitExtraMethod RyuJit 171.3973 ns 1.05 11 Executing Unsafe code requires full trust. It can be a „no go” for Cloud! No need for pinning!
  • 12. Stackalloc is the fastest way to allocate small chunks of memory in .NET 12
  • 13. 13 Allocation Deallocation Usage Managed < 85 KB Very cheap (NextObjPtr) • non-deterministic • Expensive! • GC: stop the world • Very easy • Common • Safe Managed: LOH Acceptable cost (free list management) The same as above &: • Fragmentation (LOH) • LOH = Gen 2 = Full GC Native: Stackalloc Very cheap • Deterministic • Very cheap • Unsafe • Not common • Limited Native: Marshal Acceptable cost (free list management) • Deterministic • Very cheap • On demand
  • 14. Span (Slice) It provides a uniform API for working with: • Unmanaged memory buffers • Arrays and subarrays • Strings and substrings It’s fully type-safe and memory-safe. Almost no overhead. It’s a Value Type. 15
  • 15. Supports any memory byte* pointerToStack = stackalloc byte[256]; Span<byte> stackMemory = new Span<byte>(pointerToStack, 256); Span<byte> stackMemory = stackalloc byte[256]; // C# 8.0? IntPtr unmanagedHandle = Marshal.AllocHGlobal(256); Span<byte> unmanaged = new Span<byte>(unmanagedHandle.ToPointer(), 256); Span<byte> unmanaged = Marshal.AllocHGlobal(256); // C# 8.0? char[] array = new char[] { 'D', 'O', 'T', ' ', 'N', 'E', 'X', 'T' }; Span<char> fromArray = new Span<char>(array); 16
  • 16. Single method in the API is enough unsafe void Handle(byte* buffer, int length) { } void Handle(byte[] buffer) { } void Handle(Span<T> buffer) { } 17
  • 17. Uniform access to any kind of contiguous memory public void Enumeration<T>(Span<T> buffer) { for (int i = 0; i < buffer.Length; i++) { Use(buffer[i]); } foreach (T item in buffer) { Use(item); } } 18
  • 18. Span for new runtimes • CoreCLR 1.2 • CLR 4.6.3? 4.6.4? 19
  • 19. Span for existing runtimes 20 .NET 4.5+, .NET Standard 1.0
  • 20. Make subslices without allocations ReadOnlySpan<char> subslice = ".NET Core: Performance Storm!" .Slice(start: 0, length: 9); 21
  • 22. Possible usages • Formatting • Base64/Unicode encoding • HTTP Parsing/Writing • Compression/Decompression • XML/JSON parsing/writing • Binary reading/writing • & more!! 23
  • 24. .NET Managed Heap* 25 G e n 0 G e n 1 Gen 2 LOH * - simplified, Workstation mode or view per logical processor in Server mode FULL GC
  • 25. ArrayPool • System.Buffers package • Provides a resource pool that enables reusing instances of T[] • Arrays allocated on managed heap with new operator • The default maximum length of each array in the pool is 2^20 (1024*1024 = 1 048 576) 26
  • 26. ArrayPool: Sample var pool = ArrayPool<byte>.Shared; byte[] buffer = pool.Rent(minLength); try { Use(buffer); } finally { pool.Return(buffer); } 27
  • 29. 1 MB 31 Method Median StdDev Scaled Delta Gen 0 Gen 1 Gen 2 stackalloc 51,689.8611 ns 3,343.26 ns 3.76 275.9% - - - New 13,750.9839 ns 974.0229 ns 1.00 Baseline - - 23 935 NativePool.Shared 186.1173 ns 12.6833 ns 0.01 -98.6% - - - ArrayPool.Shared 61.4539 ns 3.4862 ns 0.00 -99.6% - - - SizeAware 54.5332 ns 2.1022 ns 0.00 -99.6% - - -
  • 31. Async on hotpath Task<T> SmallMethodExecutedVeryVeryOften() { if(CanRunSynchronously()) // true most of the time { return Task.FromResult(ExecuteSynchronous()); } return ExecuteAsync(); } 33
  • 32. Async on hotpath: consuming method while (true) { var result = await SmallMethodExecutedVeryVeryOften(); Use(result); } 34
  • 33. ValueTask<T>: the idea • Wraps a TResult and Task<TResult>, only one of which is used • It should not replace Task, but help in some scenarios when: • method returns Task<TResult> • and very frequently returns synchronously (fast) • and is invoked so often that cost of allocation of Task<TResult> is a problem 37
  • 34. Sample implementation of ValueTask usage ValueTask<T> SampleUsage() { if (IsFastSynchronousExecutionPossible()) { return ExecuteSynchronous(); // INLINEABLE!!! } return new ValueTask<T>(ExecuteAsync()); } T ExecuteSynchronous() { } Task<T> ExecuteAsync() { } 38
  • 35. How to consume ValueTask var valueTask = SampleUsage(); // INLINEABLE if(valueTask.IsCompleted) { Use(valueTask.Result); } else { Use(await valueTask.AsTask()); // NO INLINING } 39
  • 36. ValueTask<T>: usage && gains • Sample usage: • Sockets (already used in ASP.NET Core) • File Streams • ADO.NET Data readers • Gains: • Less heap allocations • Method inlining is possible! • Facts • Skynet 146ns for Task, 16ns for ValueTask • Tech Empower (Plaintext) +2.6% 40
  • 39. Pipelines (Channels) • „ high performance zero-copy buffer-pool-managed asynchronous message pipes” – Marc Gravell from Stack Overflow • Pipeline pushes data to you rather than having you pull. • When writing to a pipeline, the caller allocates memory from the pipeline directly. • No new memory is allocated. Only pooled memory buffer is used. 43
  • 40. Simplified Flow Asks for a memory buffer. Writes the data to the buffer. Returns pooled memory. Starts awaiting for the data. Reads the data from buffer. Uses low-allocating Span based apis (parsing etc). Returns the memory to the pool when done. 44
  • 41. System.Runtime.CompilerServices.Unsafe T As<T>(object o) where T : class; void* AsPointer<T>(ref T value); void Copy<T>(void* destination, ref T source); void Copy<T>(ref T destination, void* source); void CopyBlock(void* destination, void* source, uint byteCount); void InitBlock(void* startAddress, byte value, uint byteCount); T Read<T>(void* source); int SizeOf<T>(); void Write<T>(void* destination, T value); 45
  • 42. Supported frameworks 46 Package name .NET Standard .NET Framework Release Nuget feed System.Slices 1.0 4.5 1.2? Clr/fxlab System.Buffers 1.1 4.5.1 1.0 nuget.org System.Threading.Task.Extensions 1.0 4.5 1.0 nuget.org System.Runtime.CompilerServices.Unsafe 1.0 4.5 1.0 corefx
  • 43. Questions? Contact: @SitnikAdam Adam.Sitnik@gmail.com You can find the benchmarks at https://github.com/adamsitnik/DotNetCorePerformance https://github.com/adamsitnik/CSharpSevenBenchmarks