Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Memory Management, C# 7.2 and Span<T>

slang25
March 25, 2018

Memory Management, C# 7.2 and Span<T>

A tour of .NET memory management, new C# features and Span

slang25

March 25, 2018
Tweet

More Decks by slang25

Other Decks in Technology

Transcript

  1. 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
  2. Types ▸ Value types ▹ Structs ▹ Enums ▹ Bool

    ▹ Int, Float, Short, Long… ▹ Byte ▸ Reference types ▹ Class ▹ Interface ▹ Array ▹ String ▹ Delegate
  3. 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)
  4. 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
  5. “ The great Eric Lippert once wrote “The Stack Is

    An Implementation Detail”, and basically that’s not true anymore. - Jon Skeet
  6. Span<T> - Why stack-only? ▸ Safe lifetime - cannot outlive

    stack memory ▸ Safe concurrency - No struct tearing ▸ It’s fast!
  7. Use Cases ▸ Alternative to unsafe code ▸ Parsing text

    ▸ Sharing partial parts of memory
  8. Problem with pointers ▸ Requires GC pinning (for heap memory)

    ▸ Mustn’t escape pointer (for stack) ▸ No bounds checking ▸ Unsafe code blocks
  9. Span<T> Framework APIs netstandard2.0 ❌ netstandard2.1 ✅ Today Next netcoreapp2.1

    ✅ netcoreapp2.0 ❌ netcoreapp2.2 ✅ netcoreapp2.3 ✅ netcoreapp3.0 ✅ net472 ❌ net48 ❌ net49 ❓ ❓
  10. Related topics ▸ ReadOnlySpan<T> ▸ Memory<T> & ReadOnlyMemory<T> ▸ System.Runtime.CompilerServices.Unsafe

    ▸ MemoryMarshal.AsBytes(span) ▸ MemoryMarshal.Cast<TFrom,TTo>(span)
  11. Case study JustEat.StatsD PRs Low hanging fruit: #55, #59, #63,

    #65 Master class by dv00d00: #104 - Zero Allocations
  12. 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