Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Memory Management, C# 7.2 and Span<T>
Search
slang25
March 25, 2018
Technology
2
1.8k
Memory Management, C# 7.2 and Span<T>
A tour of .NET memory management, new C# features and Span
slang25
March 25, 2018
Tweet
Share
More Decks by slang25
See All by slang25
Async in C# - The Good, the Bad and the Ugly
slang25
4
2k
Other Decks in Technology
See All in Technology
スタートアップ1人目QAエンジニアが QAチームを立ち上げ、“個”からチーム、 そして“組織”に成長するまで / How to set up QA team at reiwatravel
mii3king
2
1.5k
目の前の仕事と向き合うことで成長できる - 仕事とスキルを広げる / Every little bit counts
soudai
24
7.1k
『衛星データ利用の方々にとって近いようで触れる機会のなさそうな小話 ~ 衛星搭載ソフトウェアと衛星運用ソフトウェア (実物) を動かしながらわいわいする編 ~』 @日本衛星データコミニティ勉強会
meltingrabbit
0
150
「海外登壇」という 選択肢を与えるために 〜Gophers EX
logica0419
0
710
エンジニアの育成を支える爆速フィードバック文化
sansantech
PRO
3
1.1k
JEDAI Meetup! Databricks AI/BI概要
databricksjapan
0
100
PHPカンファレンス名古屋-テックリードの経験から学んだ設計の教訓
hayatokudou
2
300
Swiftの “private” を テストする / Testing Swift "private"
yutailang0119
0
130
トラシューアニマルになろう ~開発者だからこそできる、安定したサービス作りの秘訣~
jacopen
2
2k
君も受託系GISエンジニアにならないか
sudataka
2
430
OpenID BizDay#17 KYC WG活動報告(法人) / 20250219-BizDay17-KYC-legalidentity
oidfj
0
250
2/18/25: Java meets AI: Build LLM-Powered Apps with LangChain4j
edeandrea
PRO
0
120
Featured
See All Featured
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Code Reviewing Like a Champion
maltzj
521
39k
Music & Morning Musume
bryan
46
6.3k
Facilitating Awesome Meetings
lara
52
6.2k
For a Future-Friendly Web
brad_frost
176
9.5k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
3.7k
GraphQLの誤解/rethinking-graphql
sonatard
68
10k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5.2k
Testing 201, or: Great Expectations
jmmastey
42
7.2k
Keith and Marios Guide to Fast Websites
keithpitt
411
22k
Done Done
chrislema
182
16k
Transcript
Memory Management, C# 7.2 and Span<T>
HELLO! F# |> I ❤ 9 years of experience in
.NET Organiser of Bristol F# meetup and DDD South West You can find me at @stuartblang & http://stuartlang.uk
None
Rust
• FAST • SAFE • MAINTAINABLE Can C# have all
3?
C# as a high performance language
C# as a high performance language
Performance where it matters Fram eworks Libraries
Always Measure
Measure with... ▸ Memory Performance Counters ▸ BenchmarkDotNet ▸ dotMemory
▸ Visual Studio
How it works
None
None
“ The Stack Is An Implementation Detail. - Eric Lippert
Part One Part Two
Types ▸ Value types ▹ Structs ▹ Enums ▹ Bool
▹ Int, Float, Short, Long… ▹ Byte ▸ Reference types ▹ Class ▹ Interface ▹ Array ▹ String ▹ Delegate
Code Stack a=42 Stack x(ref) Heap object: array{1,2,3} sharplab.io demo
Code - behaviour
Stack Credit: http://www.i-programmer.info/ebooks/deep-c/363
Heap Small Object Heap Large Object Heap Gen 0 Gen
1 Gen 2
Heap Credit: https://www.dynatrace.com/resources/ebooks/javabook/how-garbage-collection-works/
Great Resource ▸ http://benhall.io/a-super-simplified-exp lanation-of-net-garbage-collection/
Stack vs Heap What? Lifetime When disposed? Time to dispose
Stack Local values Local references (just the ref part) Stack frame Deterministic Constant (near instant) Heap Reference object instances Unrestricted GC non-deterministic It depends (non-trivial)
Watch out for hidden allocations ▸ Let’s see some examples
Watch out for hidden allocations
Watch out for hidden allocations
Watch out for hidden allocations
Watch out for hidden allocations
Plugins ▸ R# Heap Allocations Viewer ▸ Roslyn Clr Heap
Allocation Analyzer
None
In Parameters
In Parameters - cont. ▸ Essentially readonly ref ▸ Where
you want to want to pass by-ref for performance, with the safety and behaviour or by-value ▸ Watch out for copying with invoking methods on non-readonly structs
Ref extension methods
Ref locals ▸ Reference semantics with value types
Ref locals ▸ Can be thought of as aliases
Ref returns
Ref Struct ▸ Aka ref-like ▸ Stack-only! ▸ To support
Span<T>
Ref Struct
“ The great Eric Lippert once wrote “The Stack Is
An Implementation Detail”, and basically that’s not true anymore. - Jon Skeet
Span<T> ▸ Abstraction over arbitrary memory Span<T> Marshal.AllocHGlobal() stackalloc []
new []
Span<T>
Span<T>
Span<T> - Why stack-only? ▸ Safe lifetime - cannot outlive
stack memory ▸ Safe concurrency - No struct tearing ▸ It’s fast!
Span<T> - Other properties ▸ Efficient representation ▸ GC tracking
- refs will be maintained by GC
Use Cases ▸ Alternative to unsafe code ▸ Parsing text
▸ Sharing partial parts of memory
Problem with pointers ▸ Requires GC pinning (for heap memory)
▸ Mustn’t escape pointer (for stack) ▸ No bounds checking ▸ Unsafe code blocks
Problem with pointers
Credit: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/stackalloc
None
You can still pin
You can still pin - in C# 7.3
BenchmarkDotNet
None
None
Results
C# 8 - Slicing with Ranges demo
None
None
Span<T> Framework APIs netstandard2.0 ❌ netstandard2.1 ✅ Today Next netcoreapp2.1
✅ netcoreapp2.0 ❌ netcoreapp2.2 ✅ netcoreapp2.3 ✅ netcoreapp3.0 ✅ net472 ❌ net48 ❌ net49 ❓ ❓
Related topics ▸ ReadOnlySpan<T> ▸ Memory<T> & ReadOnlyMemory<T> ▸ System.Runtime.CompilerServices.Unsafe
▸ MemoryMarshal.AsBytes(span) ▸ MemoryMarshal.Cast<TFrom,TTo>(span)
Libraries using Span<T> (just some) ▸ Utf8Json ▸ SpanJson ▸
ZeroFormatter ▸ StackExchange.Redis
Case study JustEat.StatsD PRs Low hanging fruit: #55, #59, #63,
#65 Master class by dv00d00: #104 - Zero Allocations
Good Reads ▸ Adam Sitnik - Span ▸ Marc Gravell
- Spans and ref Parts 1 & 2 ▸ Span<T> spec ▸ Vladimir Sadov ▸ All About Span: Exploring a New .NET Mainstay - Stephen Toub ▸ Maarten Balliauw
Summary
THANKS! Any questions? You can find me at @stuartblang