Recent changes with C# 7 returning values by references, ref locals and ref returns, readonly struct, ref struct, in modifier, the Span<T> type and how it is used with libraries - performance improvements on the string type, stream overloads with Span parameters, and the System.IO.Pipeline library
3. Ref / Value
• class
• Pass by reference
• Stored on the heap
Reference Types
• struct
• Pass by value
• Stored on the stack – or the heap
• Boxing!
Value Types
5. Christian Nagel
• Training
• Coaching
• Consulting
• Development
• Microsoft MVP
• www.cninnovation.com
• csharp.christiannagel.com
6. Struct
.NET Design
Guidelines
• Do not provide a default constructor
• Not allowed by C#
• Do not define mutable value types
• Developers might not be aware to mutate a
copy
• Do ensure that zero/false/null state is valid
• Prevents accidential creation of invalid instances
• Do implement IEquatable<T>
• Object.Equals causes boxing
• Do not explicitly extend value types
• Not allowed by C#
7. Rule: "Do not define mutable value types"!
Ausnahmen!
short/int/long/
float/double
Tuples
8.
9.
10. readonly struct
• C# 7.2
readonly struct MyStruct
{
public MyStruct(int myProperty) => MyProperty = myProperty;
public int MyProperty { get; }
}
12. ref return / ref local
• Eine Referenz auf einen Value Type zurück liefern
• ref local
public class Container
{
public Container(int[] data) => _data = data;
private int[] _data;
public ref int GetItem(int index) => ref _data[index];
}
ref int item = ref c.GetItem(3);
13. ref readonly
• Eine Referenz, aber nicht änderbar
public ref readonly int GetItem(int index) => ref _data[index];
ref readonly int item = ref c.GetItem(3);
// item = 4; // error – cannot be changed!
14. in Parameter Modifier
• Pass by ref – aber nicht änderbar
void PassByReference(in int x)
{
// cannot change x
}
18. String Performance (.NET Core 2.1)
• String.Equal
• String.IndexOf, String.LastIndexOf
• String.ToLower
• String.Split
• String.Format
• StringBuilder.Append
• int.Parse
• Algorithms from vectorized
computing (like used with Span<T>)
• Using Span<T> internally
• Reducing allocations
• Fast paths for common scenarios
19. ArrayPool
Werden viele Arrays dynamisch erzeugt?
ArrayPool verwaltet Arrays
Rent Arrays vom Pool
Return Arrays zum Pool
Thread safe!
.NET Core 2.1 MemoryPool für Buffer
21. Pipelines
• Management von Buffers
• Wird von Kestrel und SignalR
verwendet
• System.IO.Pipelines
• Pipe
• allocates and manages memory
• PipeReader / PipeWriter
• read and write side of the pipe
• ReadOnlySequence
• linked list of buffers