SlideShare a Scribd company logo
1 of 26
A (brief) overview of Span<T>
(and ReadOnlySpan<T> and Memory<T> and ReadOnlyMemory<T>)
DAVID WENGIER
@davidwengier
What is Span<T>?
- Stephen Toub, MSDN Magazine, January 2018
https://msdn.microsoft.com/en-us/magazine/mt814808
“System.Span<T> is a new value type at the heart of .NET [that]
enables the representation of contiguous regions of arbitrary
memory”
What is Span<T>?
• struct
• Part of System.Memory, available on Nuget
• Currently at rc1 version (prerelease)
• .NET Standard 1.0 so can be used in .NET 4.5+
• C# 7.2-ish
“System.Span<T> is a new value type at the heart of .NET [that]
enables the representation of contiguous regions of arbitrary
memory”
What is Span<T>?
• High performance, low (no) overhead
• Framework, CLR, JIT and GC support
• Provides memory and type safety
• Avoids the need for unsafe code
“System.Span<T> is a new value type at the heart of .NET [that]
enables the representation of contiguous regions of arbitrary
memory”
What is Span<T>?
• Native/unmanaged memory (P/Invoke)
• Managed memory (.NET types)
• Stack memory (stackalloc)
“System.Span<T> is a new value type at the heart of .NET [that]
enables the representation of contiguous regions of arbitrary
memory”
What is Span<T>?
• Think of it like having an array to access raw memory
var arr = new byte[10];
Span<byte> bytes = arr;
bytes[0] = 42;
Assert.True(arr[0] == 42);
Span<byte> slice = bytes.Slice(4, 3);
slice[0] = 43;
Assert.True(bytes[4] == 43);
Assert.True(arr[4] == 43);
slice[5] = 44; // IndexOutOfRangeException
HeapStack
0x01
0x02
0x03
0x04
0x05
0x06
string plate = “YGG871”;
plate = plate.Substring(3);
int num = int.Parse(plate);
plate 0x01
“YGG871”
plate 0x02
“871”
num 871
HeapStack
0x01
0x02
0x03
0x04
0x05
0x06
string plate = “YGG871”;
ReadOnlySpan<char> s = plate.AsSpan();
s = s.Slice(3);
int num = int.Parse(s);
plate 0x01
“YGG871”
0x01
0
6
3
num 871
span
offset
pointer
length
.NET Framework 4.5+ - slow span
HeapStack
0x01
0x02
0x03
0x04
0x05
0x06
string plate = “YGG871”;
ReadOnlySpan<char> s = plate.AsSpan();
s = s.Slice(3);
int num = int.Parse(s);
plate 0x01
“YGG871”
0x01+3
3
num 871
ref
span
length
pointer
.NET Core 2.0+ – fast span
* From Adam Sitnik - http://adamsitnik.com/Span/
Method Job Mean StdDev
SpanIndexer_G
et
.NET 4.6 0.6054 ns 0.0007 ns
SpanIndexer_G
et
.NET Core 1.1 0.6047 ns 0.0008 ns
SpanIndexer_G
et
.NET Core 2.0 0.5333 ns 0.0006 ns
SpanIndexer_S
et
.NET 4.6 0.6059 ns 0.0007 ns
SpanIndexer_S
et
.NET Core 1.1 0.6042 ns 0.0002 ns
SpanIndexer_S
et
.NET Core 2.0 0.5205 ns 0.0003 n
Method
String
Length
Mean StdDev Scaled Gen 0
Allocated
*
Substring 10 8.277 ns 0.1938 ns 4.54 0.0191 40 B
Slice 10 1.822 ns 0.0383 ns 1.00 - 0 B
Substring 1000 85.518 ns 1.3474 ns 47.22 0.4919 1032 B
Slice 1000 1.811 ns 0.0205 ns 1.00 - 0 B
* Not including original string
Framework Support
https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/Int32.cs
Framework Support
Framework Support
// RandomStringLoop
var stringChars = new char[Length];
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = (char)(random.Next(0, 10) + '0');
}
return new string(stringChars);
// RandomStringEnumerable
return new string(Enumerable.Repeat("", Length)
.Select(s => (char)(random.Next(0, 10) + '0')).ToArray());
// RandomStringSpan
return string.Create(Length, random, (Span<char> chars, Random r) =>
{
for (int i = 0; i < chars.Length; i++)
{
chars[i] = (char)(r.Next(0, 10) + '0');
}
});
Method Length Mean Scaled Allocated
RandomStringSpan 10 150.29 ns 1.00 48 B
RandomStringLoop 10 156.16 ns 1.04 96 B
RandomStringEnumerable 10 340.26 ns 2.27 192 B
RandomStringSpan 100 1,314.91 ns 1.00 232 B
RandomStringLoop 100 1,361.57 ns 1.04 456 B
RandomStringEnumerable 100 2,140.91 ns 1.63 552 B
RandomStringSpan 1000 12,461.32 ns 1.00 2032 B
RandomStringLoop 1000 14,073.65 ns 1.13 4056 B
RandomStringEnumerable 1000 20,354.63 ns 1.63 4152 B
When do mere mortals use it?
public static bool ContainsCapitalLetters(string s)
{
for (int i = 0; i < s.Length; i++)
{
if (char.IsUpper(s[i]))
{
return true;
}
}
return false;
}
public static int Sum(int[] a)
{
int sum = 0;
for (int i = 0; i < a.Length; i++)
{
sum += a[i];
}
return sum;
}
When do mere mortals use it?
public static bool ContainsCapitalLetters(ReadOnlySpan<char> s)
{
for (int i = 0; i < s.Length; i++)
{
if (char.IsUpper(s[i]))
{
return true;
}
}
return false;
}
public static int Sum(ReadOnlySpan<int> a)
{
int sum = 0;
for (int i = 0; i < a.Length; i++)
{
sum += a[i];
}
return sum;
}
Limitations
• Can only live on the stack
• Implemented as a ref struct
• Can only be contained by ref structs
ref structs
Structs that can exist only on the stack. New in C# 7.2
• Can’t implement interfaces
• Can’t be used as generic type arguments
• Can’t be boxed to object
• Can’t be passed in to - or used in places inside - of async methods,
iterators, nested functions or query expressions
async Task DoSomethingAsync(Span<byte> buffer)
{
buffer[0] = 0;
await Something();
buffer[0] = 1;
}
async Task DoSomethingAsync(Span<byte> buffer)
{
SomethingClass cl = new SomethingClass()
cl.buffer = buffer;
cl.StartSomething();
}
private class SomethingClass
{
public Span<byte> buffer; // illegal
public void Start_Something()
{
buffer[0] = 0;
DoMagicAsyncStuff().ContinueWith(End_Something);
}
public void End_Something()
{
buffer[0] = 1;
}
}
Memory<T>
• “Normal” struct
• Not as performant as Span
• Can be used in more places than Span (ie, doesn’t have the
limitations)
Memory<T>
async Task DoSomethingAsync(Span<byte> buffer)
{
buffer[0] = 0;
await Something(); // Bang!
buffer[0] = 1;
}
async Task DoSomethingAsync(Memory<byte> buffer)
{
buffer.Span[0] = 0;
await Something(); // Totally fine
buffer.Span[0] = 1;
}
Memory<T>
public struct Memory<T>
{
private int _offset;
private int _length;
private int _pointer;
private byte[] _data; // really OwnedMemory<T>
public Span<T> Span => new Span<T>(_data, _pointer, _offset, _length);
}
* Not real
TechEmpower Plaintext
Round 14
Round 15
DAVID WENGIER
@davidwengier
Thank you!
Questions?

More Related Content

What's hot

Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Daniel Lemire
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
Patterns of 64-bit errors in games
Patterns of 64-bit errors in gamesPatterns of 64-bit errors in games
Patterns of 64-bit errors in gamesAndrey Karpov
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4nomaddo
 
Sparse Data Structures for Weighted Bipartite Matching
Sparse Data Structures for Weighted Bipartite Matching Sparse Data Structures for Weighted Bipartite Matching
Sparse Data Structures for Weighted Bipartite Matching Jason Riedy
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C ProgrammingDevoAjit Gupta
 
A nice 64-bit error in C
A  nice 64-bit error in CA  nice 64-bit error in C
A nice 64-bit error in CPVS-Studio
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
String in c programming
String in c programmingString in c programming
String in c programmingDevan Thakur
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...MITSUNARI Shigeo
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT LATHA LAKSHMI
 

What's hot (20)

Data type
Data typeData type
Data type
 
Strings
StringsStrings
Strings
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)
 
AA-sort with SSE4.1
AA-sort with SSE4.1AA-sort with SSE4.1
AA-sort with SSE4.1
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Patterns of 64-bit errors in games
Patterns of 64-bit errors in gamesPatterns of 64-bit errors in games
Patterns of 64-bit errors in games
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4
 
Sparse Data Structures for Weighted Bipartite Matching
Sparse Data Structures for Weighted Bipartite Matching Sparse Data Structures for Weighted Bipartite Matching
Sparse Data Structures for Weighted Bipartite Matching
 
presentation
presentationpresentation
presentation
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
A nice 64-bit error in C
A  nice 64-bit error in CA  nice 64-bit error in C
A nice 64-bit error in C
 
Strings
StringsStrings
Strings
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
String in c programming
String in c programmingString in c programming
String in c programming
 
String.ppt
String.pptString.ppt
String.ppt
 
Strings in c
Strings in cStrings in c
Strings in c
 
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
String in c
String in cString in c
String in c
 

Similar to A (brief) overview of Span<T>

State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net PerformanceCUSTIS
 
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.pptxTamir Dresher
 
primitive data types
 primitive data types primitive data types
primitive data typesJadavsejal
 
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# 8Christian Nagel
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp fullVõ Hòa
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
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 AndroidIntel® Software
 
The Ring programming language version 1.9 book - Part 100 of 210
The Ring programming language version 1.9 book - Part 100 of 210The Ring programming language version 1.9 book - Part 100 of 210
The Ring programming language version 1.9 book - Part 100 of 210Mahmoud Samir Fayed
 
PPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.TechPPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.Techssuser2678ab
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityDefconRussia
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centrejatin batra
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 
OpenStack Congress and Datalog (English)
OpenStack Congress and Datalog (English)OpenStack Congress and Datalog (English)
OpenStack Congress and Datalog (English)Motonori Shindo
 
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-OptimisationsMatt Warren
 

Similar to A (brief) overview of Span<T> (20)

State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
 
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
 
primitive data types
 primitive data types primitive data types
primitive data types
 
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
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
Modern C++
Modern C++Modern C++
Modern C++
 
8871077.ppt
8871077.ppt8871077.ppt
8871077.ppt
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
C
CC
C
 
C++ process new
C++ process newC++ process new
C++ process new
 
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
 
The Ring programming language version 1.9 book - Part 100 of 210
The Ring programming language version 1.9 book - Part 100 of 210The Ring programming language version 1.9 book - Part 100 of 210
The Ring programming language version 1.9 book - Part 100 of 210
 
PPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.TechPPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.Tech
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
OpenStack Congress and Datalog (English)
OpenStack Congress and Datalog (English)OpenStack Congress and Datalog (English)
OpenStack Congress and Datalog (English)
 
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
 

More from 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
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsDavid Wengier
 
Performance and Benchmarking
Performance and BenchmarkingPerformance and Benchmarking
Performance and BenchmarkingDavid Wengier
 

More from 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
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo Skills
 
Performance and Benchmarking
Performance and BenchmarkingPerformance and Benchmarking
Performance and Benchmarking
 

Recently uploaded

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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...Drew Madelung
 
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...Miguel Araújo
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
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)wesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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...
 
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...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
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)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

A (brief) overview of Span<T>

  • 1. A (brief) overview of Span<T> (and ReadOnlySpan<T> and Memory<T> and ReadOnlyMemory<T>) DAVID WENGIER @davidwengier
  • 2. What is Span<T>? - Stephen Toub, MSDN Magazine, January 2018 https://msdn.microsoft.com/en-us/magazine/mt814808 “System.Span<T> is a new value type at the heart of .NET [that] enables the representation of contiguous regions of arbitrary memory”
  • 3. What is Span<T>? • struct • Part of System.Memory, available on Nuget • Currently at rc1 version (prerelease) • .NET Standard 1.0 so can be used in .NET 4.5+ • C# 7.2-ish “System.Span<T> is a new value type at the heart of .NET [that] enables the representation of contiguous regions of arbitrary memory”
  • 4. What is Span<T>? • High performance, low (no) overhead • Framework, CLR, JIT and GC support • Provides memory and type safety • Avoids the need for unsafe code “System.Span<T> is a new value type at the heart of .NET [that] enables the representation of contiguous regions of arbitrary memory”
  • 5. What is Span<T>? • Native/unmanaged memory (P/Invoke) • Managed memory (.NET types) • Stack memory (stackalloc) “System.Span<T> is a new value type at the heart of .NET [that] enables the representation of contiguous regions of arbitrary memory”
  • 6. What is Span<T>? • Think of it like having an array to access raw memory
  • 7. var arr = new byte[10]; Span<byte> bytes = arr; bytes[0] = 42; Assert.True(arr[0] == 42); Span<byte> slice = bytes.Slice(4, 3); slice[0] = 43; Assert.True(bytes[4] == 43); Assert.True(arr[4] == 43); slice[5] = 44; // IndexOutOfRangeException
  • 8. HeapStack 0x01 0x02 0x03 0x04 0x05 0x06 string plate = “YGG871”; plate = plate.Substring(3); int num = int.Parse(plate); plate 0x01 “YGG871” plate 0x02 “871” num 871
  • 9. HeapStack 0x01 0x02 0x03 0x04 0x05 0x06 string plate = “YGG871”; ReadOnlySpan<char> s = plate.AsSpan(); s = s.Slice(3); int num = int.Parse(s); plate 0x01 “YGG871” 0x01 0 6 3 num 871 span offset pointer length .NET Framework 4.5+ - slow span
  • 10. HeapStack 0x01 0x02 0x03 0x04 0x05 0x06 string plate = “YGG871”; ReadOnlySpan<char> s = plate.AsSpan(); s = s.Slice(3); int num = int.Parse(s); plate 0x01 “YGG871” 0x01+3 3 num 871 ref span length pointer .NET Core 2.0+ – fast span
  • 11. * From Adam Sitnik - http://adamsitnik.com/Span/ Method Job Mean StdDev SpanIndexer_G et .NET 4.6 0.6054 ns 0.0007 ns SpanIndexer_G et .NET Core 1.1 0.6047 ns 0.0008 ns SpanIndexer_G et .NET Core 2.0 0.5333 ns 0.0006 ns SpanIndexer_S et .NET 4.6 0.6059 ns 0.0007 ns SpanIndexer_S et .NET Core 1.1 0.6042 ns 0.0002 ns SpanIndexer_S et .NET Core 2.0 0.5205 ns 0.0003 n
  • 12. Method String Length Mean StdDev Scaled Gen 0 Allocated * Substring 10 8.277 ns 0.1938 ns 4.54 0.0191 40 B Slice 10 1.822 ns 0.0383 ns 1.00 - 0 B Substring 1000 85.518 ns 1.3474 ns 47.22 0.4919 1032 B Slice 1000 1.811 ns 0.0205 ns 1.00 - 0 B * Not including original string
  • 15. Framework Support // RandomStringLoop var stringChars = new char[Length]; for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = (char)(random.Next(0, 10) + '0'); } return new string(stringChars); // RandomStringEnumerable return new string(Enumerable.Repeat("", Length) .Select(s => (char)(random.Next(0, 10) + '0')).ToArray()); // RandomStringSpan return string.Create(Length, random, (Span<char> chars, Random r) => { for (int i = 0; i < chars.Length; i++) { chars[i] = (char)(r.Next(0, 10) + '0'); } });
  • 16. Method Length Mean Scaled Allocated RandomStringSpan 10 150.29 ns 1.00 48 B RandomStringLoop 10 156.16 ns 1.04 96 B RandomStringEnumerable 10 340.26 ns 2.27 192 B RandomStringSpan 100 1,314.91 ns 1.00 232 B RandomStringLoop 100 1,361.57 ns 1.04 456 B RandomStringEnumerable 100 2,140.91 ns 1.63 552 B RandomStringSpan 1000 12,461.32 ns 1.00 2032 B RandomStringLoop 1000 14,073.65 ns 1.13 4056 B RandomStringEnumerable 1000 20,354.63 ns 1.63 4152 B
  • 17. When do mere mortals use it? public static bool ContainsCapitalLetters(string s) { for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s[i])) { return true; } } return false; } public static int Sum(int[] a) { int sum = 0; for (int i = 0; i < a.Length; i++) { sum += a[i]; } return sum; }
  • 18. When do mere mortals use it? public static bool ContainsCapitalLetters(ReadOnlySpan<char> s) { for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s[i])) { return true; } } return false; } public static int Sum(ReadOnlySpan<int> a) { int sum = 0; for (int i = 0; i < a.Length; i++) { sum += a[i]; } return sum; }
  • 19. Limitations • Can only live on the stack • Implemented as a ref struct • Can only be contained by ref structs
  • 20. ref structs Structs that can exist only on the stack. New in C# 7.2 • Can’t implement interfaces • Can’t be used as generic type arguments • Can’t be boxed to object • Can’t be passed in to - or used in places inside - of async methods, iterators, nested functions or query expressions
  • 21. async Task DoSomethingAsync(Span<byte> buffer) { buffer[0] = 0; await Something(); buffer[0] = 1; } async Task DoSomethingAsync(Span<byte> buffer) { SomethingClass cl = new SomethingClass() cl.buffer = buffer; cl.StartSomething(); } private class SomethingClass { public Span<byte> buffer; // illegal public void Start_Something() { buffer[0] = 0; DoMagicAsyncStuff().ContinueWith(End_Something); } public void End_Something() { buffer[0] = 1; } }
  • 22. Memory<T> • “Normal” struct • Not as performant as Span • Can be used in more places than Span (ie, doesn’t have the limitations)
  • 23. Memory<T> async Task DoSomethingAsync(Span<byte> buffer) { buffer[0] = 0; await Something(); // Bang! buffer[0] = 1; } async Task DoSomethingAsync(Memory<byte> buffer) { buffer.Span[0] = 0; await Something(); // Totally fine buffer.Span[0] = 1; }
  • 24. Memory<T> public struct Memory<T> { private int _offset; private int _length; private int _pointer; private byte[] _data; // really OwnedMemory<T> public Span<T> Span => new Span<T>(_data, _pointer, _offset, _length); } * Not real