SlideShare uma empresa Scribd logo
1 de 53
Direction of C# as a High-
Performance Language
Igor Fesenko
SoftServe Inc.
@ky7m
Who am I?
• Leading software development
projects
• Passionate about high burst/HPC
systems
• Design cloud ready software solutions
• SoftServe .NET Community leader
• Conference speaker and trainer
• More… go to ifesenko.com
“Performance of my code is awesome.”
Developer
“…premature optimization is the root of all evil…”
Donald Knuth
• Productivity and ease of use
• Built-in safety
• Powerful async and concurrency models
• Mature ecosystem of tools and libraries
Why C#?
@ky7m #dotnet
#fwdays
Problem?
@ky7m #dotnet
#fwdays
.NET
@ky7m #dotnet
#fwdays
.NE
T
Problem?
@ky7m #dotnet
#fwdays
• Garbage collection
• Allocation-rich APIs and patterns
Why Not C#?
@ky7m #dotnet
#fwdays
Memory Allocations Everywhere
Code Generation
@ky7m #dotnet
#fwdays
• Just-In-Time (JIT) - CoreCLR
• fast compile times
• simple
• decent code quality
• Ahead-Of-Time (AOT) - CoreRT
• best code quality
• slower compile times
• complex deployment model
• Hybrid [Future]
• let the system adaptively recompile
Code Generation
@ky7m #dotnet
#fwdays
Code Generation
JIT
AOT
AOT
@ky7m #dotnet
#fwdays
• Inlining
• Flowgraph and loop analysis
• Range analysis
• SIMD and vectorization
• Dead code elimination
• …
/optimize+
@ky7m #dotnet
#fwdays
Inlining
• New stack frame
• Save return
address
• Save registers
• Call
• Restore context
@ky7m #dotnet
#fwdays
Inlining
int tmp = a; a = b; b = tmp;
void Swap<T>(ref T a, ref T b)
{
T tmp = a; a = b; b = tmp;
}
@ky7m #dotnet
#fwdays
Allocation
• Allocates up to 2
objects
• lambda
• captured stack
frame @ky7m #dotnet
#fwdays
Stop the world!
@ky7m #dotnet
#fwdays
• Generational, compacting garbage collector
• Large Object Heap (LOH) manually only
• Manual “low pause” regions
• LowLatency
• TryStartNoGCRegion
• Parallel collector for server workloads
• Server mode
• .NET 4.5 concurrent + parallel in harmony
Garbage Collection
@ky7m #dotnet
#fwdays
• Language Feature Status
• C# 7.0
• Binary Literals
• Digit Separators
• Local Functions
• Type switch
• Ref Returns
• Tuples
• Out var
• ValueTask
• …
C# 7 Features
@ky7m #dotnet
#fwdays
Who wants to be a Millionaire?
C# 6.0 Quiz
@ky7m #dotnet
#fwdays
A. All options are correct
What is the correct C# syntax to declare
the getter-only auto-property ?
Opt. 1 - public int Property1 => 42;
Opt. 2 - public int Property2 { get => 42; }
Opt. 3 - public int Property3 { get { return 42; }
B. Options 1 and 3
C. Option 3 D. I’m Java developer
A. All options are correct
D. I’m Java developer
What is the correct C# syntax to declare
the getter-only auto-property ?
Opt. 1 - public int Property1 => 42;
Opt. 2 - public int Property2 { get => 42; }
Opt. 3 - public int Property3 { get { return 42; }
A. All options are correct
D. I’m Java developer
What is the correct C# syntax to declare
the getter-only auto-property ?
Opt. 1 - public int Property1 => 42;
Opt. 2 - public int Property2 { get => 42; }
Opt. 3 - public int Property3 { get { return 42; }
Local Functions
@ky7m #dotnet
#fwdays
Local Functions
List<T> items,
values
values,
• Value Type
to build
closure
@ky7m #dotnet
#fwdays
Ref Returns
@ky7m #dotnet
#fwdays
Ref Returns
ref
ref
ref ref
place = 9;
WriteLine(array[4]); // prints 9
@ky7m #dotnet
#fwdays
Tuples
• New Tuples are value
types
@ky7m #dotnet
#fwdays
• Struct type
• Not replace Task, but help to
• drastically reduce the number of allocations
• method inlining
ValueTask<T>
@ky7m #dotnet
#fwdays
The hardest problem in computer science is
fighting the urge to solve a different, more
interesting problem than the one at hand.
Nick Lockwood
• Exposes implementation details
• Code Complexity
• Obscures Logic
• Missing Static Checks
• More Exception Handlers
• Security
• Performance
Problems with Reflection
@ky7m #dotnet
#fwdays
• Available on Nuget -
https://www.nuget.org/packages/FastMember
• Open-source -
https://github.com/mgravell/fast-member/
• Uses ILGenerator and SiteCall power
FastMember
@ky7m #dotnet
#fwdays
FastMember Example Usage
var
string // smth known at runtime
while /* some loop of data */
// obj could be static or DLR
var
string // smth known at runtime
@ky7m #dotnet
#fwdays
FastMember and SqlBulkCopy
var new
var
@ky7m #dotnet
#fwdays
• Nuget -
https://www.nuget.org/packages/System.Runtime.Co
mpilerServices.Unsafe/
• Low-level functionality for manipulating pointers
• Whole code is single IL file
System.Runtime.CompilerServices.Unsafe
@ky7m #dotnet
#fwdays
Unsafe class api
public static class Unsafe
// all methods are public static unsafe
void
void void value
int
object where class
void ref value
ref void
void InitBlock void byte uint
void CopyBlock void void uint
ref void
@ky7m #dotnet
#fwdays
With Unsafe you’re more Safe
var 10
var ref //void*
var int // int
@ky7m #dotnet
#fwdays
• One Really Big Query Expression (60-line query)
• A lot of LINQ To * (what you want)
LINQ is fantastic feature of C#!
@ky7m #dotnet
#fwdays
Even R# helps…
@ky7m #dotnet
#fwdays
• Hidden allocations
• Possible multiple enumeration
• Easy to write a non-optimal query
LINQ downsides
@ky7m #dotnet
#fwdays
• Nuget -
https://www.nuget.org/packages/LinqOptimizer.CSharp/
• Works at run-time
• Requires AsQueryExpr().Run() to LINQ methods
• Optimizes Parallel LINQ
• Specialized strategies and algorithms
LinqOptimizer
@ky7m #dotnet
#fwdays
• https://github.com/antiufo/roslyn-linq-rewrite
• Works at compile time (build step)
• No code changes
• No allocations for Expression<> trees and
enumerator boxing
• Parallel LINQ is not supported
RoslynLinqRewrite
@ky7m #dotnet
#fwdays
• https://github.com/dotnet/corefxlab/tree/master/src
/System.Slices
• Span is a simple struct that gives you uniform access
to any kind of contiguous memory
• 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.
Span (Slice)
@ky7m #dotnet
#fwdays
Make subslices without allocations
byte stackalloc byte 256
var new byte 256
char new char ’ ' 'N' 'E' 'T'
char new char
char
0 4
@ky7m #dotnet
#fwdays
• Nuget -
https://www.nuget.org/packages/System.Buffers/
• ArrayPool
• resource pool that enables reusing instances of T[]
• managed memory
• NativeBufferPool (experimental, under corefxlab)
• Unmanaged memory
• pool of Slice<T>
System.Buffers
@ky7m #dotnet
#fwdays
• Get your own instance
• ArrayPool<T>.Shared (Thread safe)
• NativeBufferPool<byte>.SharedByteBufferPool (Thread
safe)
• ArrayPool<T>.Create(int maxArrayLength, ..)
• Rent
• Specify the min size
• Bigger can be returned, don’t rely on .Length
• Finally { Return }
• Alternative - Microsoft.IO.RecyclableMemoryStream
• Provide pooling for .NET MemoryStream objects
• Limited usage
How to work with Pools
@ky7m #dotnet
#fwdays
• Heap allocation viewer
Heap Allocations Viewer R# plugin
Clr Heap Allocation Analyzer VS extension
• Roslyn analyzers
https://github.com/dotnet/roslyn-analyzers
https://github.com/Wintellect/Wintellect.Analyzers
https://github.com/DotNetAnalyzers/StyleCopAnalyzers
• Annotations
[StackOnly] - Microsoft.CodeAnalysis.StackOnlyTypes
[NoAlloc] ensures a method doesn’t allocate
[MustNotCopy] ensures a struct isn’t copied
[Scoped] ensures a value doesn’t escape the callee
... and more ...
Essential tools in your toolbox
@ky7m #dotnet
#fwdays
• C# delivers productivity and safety, good
performance from JIT to AOT and everything in
between
• A lot of features are “free”
• Structs can improve memory performance
• Less GC pressure
• Better memory locality
• Less overall space usage
• Beware of copying large structs, “ref returns”
• New features in next rev of C# and .NET: ValueTask,
ValueTuple, others
• Use power of Roslyn
Summary
• https://github.com/dotnet/corefx
• https://github.com/dotnet/coreclr
• https://github.com/dotnet/corefxlab
• https://github.com/dotnet/roslyn
• https://github.com/dotnet/corert
• https://github.com/dotnet/coreclr/blob/master/Doc
umentation/botr/readytorun-overview.md
Links
Questions
@ky7m | ifesenko.com |
ifesen@softserveinc.com

Mais conteúdo relacionado

Mais procurados

Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
Stateful, Stateless and Serverless - Running Apache Kafka® on KubernetesStateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
confluent
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
Legacy Typesafe (now Lightbend)
 

Mais procurados (20)

Datadog- Monitoring In Motion
Datadog- Monitoring In Motion Datadog- Monitoring In Motion
Datadog- Monitoring In Motion
 
Agile experiments in Machine Learning with F#
Agile experiments in Machine Learning with F#Agile experiments in Machine Learning with F#
Agile experiments in Machine Learning with F#
 
Netflix Cloud Platform and Open Source
Netflix Cloud Platform and Open SourceNetflix Cloud Platform and Open Source
Netflix Cloud Platform and Open Source
 
Netflix Open Source Meetup Season 4 Episode 2
Netflix Open Source Meetup Season 4 Episode 2Netflix Open Source Meetup Season 4 Episode 2
Netflix Open Source Meetup Season 4 Episode 2
 
Stateful stream processing of iIoT events with C# and containers
Stateful stream processing of iIoT events with C# and containersStateful stream processing of iIoT events with C# and containers
Stateful stream processing of iIoT events with C# and containers
 
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack MeetupOpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
 
Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog
 Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog
Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog
 
E2E Data Pipeline - Apache Spark/Airflow/Livy
E2E Data Pipeline - Apache Spark/Airflow/LivyE2E Data Pipeline - Apache Spark/Airflow/Livy
E2E Data Pipeline - Apache Spark/Airflow/Livy
 
NetflixOSS and ZeroToDocker Talk
NetflixOSS and ZeroToDocker TalkNetflixOSS and ZeroToDocker Talk
NetflixOSS and ZeroToDocker Talk
 
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
 
Javantura v4 - The power of cloud in professional services company - Ivan Krn...
Javantura v4 - The power of cloud in professional services company - Ivan Krn...Javantura v4 - The power of cloud in professional services company - Ivan Krn...
Javantura v4 - The power of cloud in professional services company - Ivan Krn...
 
Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
Stateful, Stateless and Serverless - Running Apache Kafka® on KubernetesStateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
 
Introduction to Streaming Distributed Processing with Storm
Introduction to Streaming Distributed Processing with StormIntroduction to Streaming Distributed Processing with Storm
Introduction to Streaming Distributed Processing with Storm
 
Elk meetup
Elk meetupElk meetup
Elk meetup
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
 
Netflix viewing data architecture evolution - EBJUG Nov 2014
Netflix viewing data architecture evolution - EBJUG Nov 2014Netflix viewing data architecture evolution - EBJUG Nov 2014
Netflix viewing data architecture evolution - EBJUG Nov 2014
 
Netflix Open Source Meetup Season 3 Episode 2
Netflix Open Source Meetup Season 3 Episode 2Netflix Open Source Meetup Season 3 Episode 2
Netflix Open Source Meetup Season 3 Episode 2
 
Lessons Learned from Building and Operating Scuba
Lessons Learned from Building and Operating ScubaLessons Learned from Building and Operating Scuba
Lessons Learned from Building and Operating Scuba
 
NetflixOSS Meetup S6E2 - Spinnaker, Kayenta
NetflixOSS Meetup S6E2 - Spinnaker, KayentaNetflixOSS Meetup S6E2 - Spinnaker, Kayenta
NetflixOSS Meetup S6E2 - Spinnaker, Kayenta
 
Gotta Persist 'Em All: Realm as Replacement for SQLite
Gotta Persist 'Em All: Realm as Replacement for SQLiteGotta Persist 'Em All: Realm as Replacement for SQLite
Gotta Persist 'Em All: Realm as Replacement for SQLite
 

Destaque

Алексей Волков "Еще несколько слов об архитектуре"
Алексей Волков "Еще несколько слов об архитектуре"Алексей Волков "Еще несколько слов об архитектуре"
Алексей Волков "Еще несколько слов об архитектуре"
Fwdays
 
Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"
Fwdays
 
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Fwdays
 
"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук
Fwdays
 

Destaque (20)

"Управление сложностью в проектах" А. Солнцев
"Управление сложностью в проектах" А. Солнцев"Управление сложностью в проектах" А. Солнцев
"Управление сложностью в проектах" А. Солнцев
 
Денис Резник "Relational Database Design. Normalize till it hurts, then Denor...
Денис Резник "Relational Database Design. Normalize till it hurts, then Denor...Денис Резник "Relational Database Design. Normalize till it hurts, then Denor...
Денис Резник "Relational Database Design. Normalize till it hurts, then Denor...
 
"Разрушаем .NET мифы" Сергей Калинец
"Разрушаем .NET мифы" Сергей Калинец"Разрушаем .NET мифы" Сергей Калинец
"Разрушаем .NET мифы" Сергей Калинец
 
Юрий Лучанинов "Критерии выбора JS-фреймворков"
Юрий Лучанинов "Критерии выбора JS-фреймворков"Юрий Лучанинов "Критерии выбора JS-фреймворков"
Юрий Лучанинов "Критерии выбора JS-фреймворков"
 
Алексей Косинский "React Native vs. React+WebView"
Алексей Косинский "React Native vs. React+WebView"Алексей Косинский "React Native vs. React+WebView"
Алексей Косинский "React Native vs. React+WebView"
 
Алексей Волков "Еще несколько слов об архитектуре"
Алексей Волков "Еще несколько слов об архитектуре"Алексей Волков "Еще несколько слов об архитектуре"
Алексей Волков "Еще несколько слов об архитектуре"
 
Юлия Пучнина "PhaserJS for advertisement: игры внутри баннеров"
Юлия Пучнина "PhaserJS for advertisement: игры внутри баннеров"Юлия Пучнина "PhaserJS for advertisement: игры внутри баннеров"
Юлия Пучнина "PhaserJS for advertisement: игры внутри баннеров"
 
Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"
 
"Архитектурный шаблон Reflex - новый подход к разработке клиент-серверных при...
"Архитектурный шаблон Reflex - новый подход к разработке клиент-серверных при..."Архитектурный шаблон Reflex - новый подход к разработке клиент-серверных при...
"Архитектурный шаблон Reflex - новый подход к разработке клиент-серверных при...
 
Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"
 
Анатолий Попель: "Формы оплаты и платёжные шлюзы"
Анатолий Попель: "Формы оплаты и платёжные шлюзы"Анатолий Попель: "Формы оплаты и платёжные шлюзы"
Анатолий Попель: "Формы оплаты и платёжные шлюзы"
 
Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"
Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"
Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"
 
Андрей Шумада | Tank.ly
Андрей Шумада | Tank.ly Андрей Шумада | Tank.ly
Андрей Шумада | Tank.ly
 
Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...
Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...
Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...
 
Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений"
Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений" Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений"
Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений"
 
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
 
Алексей Волков "Интерактивные декларативные графики на React+D3"
Алексей Волков "Интерактивные декларативные графики на React+D3"Алексей Волков "Интерактивные декларативные графики на React+D3"
Алексей Волков "Интерактивные декларативные графики на React+D3"
 
Евгений Жарков AngularJS: Good parts
Евгений Жарков AngularJS: Good partsЕвгений Жарков AngularJS: Good parts
Евгений Жарков AngularJS: Good parts
 
Трансформация команды: от инди разработки к играм с коммерческой успешностью
Трансформация команды: от инди разработки к играм с коммерческой успешностьюТрансформация команды: от инди разработки к играм с коммерческой успешностью
Трансформация команды: от инди разработки к играм с коммерческой успешностью
 
"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук
 

Semelhante a Игорь Фесенко "Direction of C# as a High-Performance Language"

Serving Deep Learning Models At Scale With RedisAI: Luca Antiga
Serving Deep Learning Models At Scale With RedisAI: Luca AntigaServing Deep Learning Models At Scale With RedisAI: Luca Antiga
Serving Deep Learning Models At Scale With RedisAI: Luca Antiga
Redis Labs
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Scaling Massive Elasticsearch Clusters
Scaling Massive Elasticsearch ClustersScaling Massive Elasticsearch Clusters
Scaling Massive Elasticsearch Clusters
Sematext Group, Inc.
 

Semelhante a Игорь Фесенко "Direction of C# as a High-Performance Language" (20)

Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
 
Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!
 
Serving Deep Learning Models At Scale With RedisAI: Luca Antiga
Serving Deep Learning Models At Scale With RedisAI: Luca AntigaServing Deep Learning Models At Scale With RedisAI: Luca Antiga
Serving Deep Learning Models At Scale With RedisAI: Luca Antiga
 
DevOpsCon 2015 - DevOps in Mobile Games
DevOpsCon 2015 - DevOps in Mobile GamesDevOpsCon 2015 - DevOps in Mobile Games
DevOpsCon 2015 - DevOps in Mobile Games
 
Performance and Abstractions
Performance and AbstractionsPerformance and Abstractions
Performance and Abstractions
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Packaging perl (LPW2010)
Packaging perl (LPW2010)Packaging perl (LPW2010)
Packaging perl (LPW2010)
 
Behat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdfBehat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdf
 
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd についてKubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
 
From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...
 
C#: Past, Present and Future
C#: Past, Present and FutureC#: Past, Present and Future
C#: Past, Present and Future
 
201811xx foredrag c_cpp
201811xx foredrag c_cpp201811xx foredrag c_cpp
201811xx foredrag c_cpp
 
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slapDEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPL
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventure
 
Scaling Massive Elasticsearch Clusters
Scaling Massive Elasticsearch ClustersScaling Massive Elasticsearch Clusters
Scaling Massive Elasticsearch Clusters
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Introduction to multicore .ppt
Introduction to multicore .pptIntroduction to multicore .ppt
Introduction to multicore .ppt
 

Mais de Fwdays

Mais de Fwdays (20)

"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
 
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast..."Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
 
"Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others..."Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others...
 
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
 
"Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv..."Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv...
 
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin..."How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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)
 

Игорь Фесенко "Direction of C# as a High-Performance Language"

  • 1. Direction of C# as a High- Performance Language Igor Fesenko SoftServe Inc. @ky7m
  • 2. Who am I? • Leading software development projects • Passionate about high burst/HPC systems • Design cloud ready software solutions • SoftServe .NET Community leader • Conference speaker and trainer • More… go to ifesenko.com
  • 3. “Performance of my code is awesome.” Developer
  • 4. “…premature optimization is the root of all evil…” Donald Knuth
  • 5. • Productivity and ease of use • Built-in safety • Powerful async and concurrency models • Mature ecosystem of tools and libraries Why C#? @ky7m #dotnet #fwdays
  • 9. • Garbage collection • Allocation-rich APIs and patterns Why Not C#? @ky7m #dotnet #fwdays
  • 12. • Just-In-Time (JIT) - CoreCLR • fast compile times • simple • decent code quality • Ahead-Of-Time (AOT) - CoreRT • best code quality • slower compile times • complex deployment model • Hybrid [Future] • let the system adaptively recompile Code Generation @ky7m #dotnet #fwdays
  • 14. • Inlining • Flowgraph and loop analysis • Range analysis • SIMD and vectorization • Dead code elimination • … /optimize+ @ky7m #dotnet #fwdays
  • 15. Inlining • New stack frame • Save return address • Save registers • Call • Restore context @ky7m #dotnet #fwdays
  • 16. Inlining int tmp = a; a = b; b = tmp; void Swap<T>(ref T a, ref T b) { T tmp = a; a = b; b = tmp; } @ky7m #dotnet #fwdays
  • 17. Allocation • Allocates up to 2 objects • lambda • captured stack frame @ky7m #dotnet #fwdays
  • 18.
  • 19. Stop the world! @ky7m #dotnet #fwdays
  • 20. • Generational, compacting garbage collector • Large Object Heap (LOH) manually only • Manual “low pause” regions • LowLatency • TryStartNoGCRegion • Parallel collector for server workloads • Server mode • .NET 4.5 concurrent + parallel in harmony Garbage Collection @ky7m #dotnet #fwdays
  • 21. • Language Feature Status • C# 7.0 • Binary Literals • Digit Separators • Local Functions • Type switch • Ref Returns • Tuples • Out var • ValueTask • … C# 7 Features @ky7m #dotnet #fwdays
  • 22. Who wants to be a Millionaire?
  • 23. C# 6.0 Quiz @ky7m #dotnet #fwdays
  • 24. A. All options are correct What is the correct C# syntax to declare the getter-only auto-property ? Opt. 1 - public int Property1 => 42; Opt. 2 - public int Property2 { get => 42; } Opt. 3 - public int Property3 { get { return 42; } B. Options 1 and 3 C. Option 3 D. I’m Java developer
  • 25. A. All options are correct D. I’m Java developer What is the correct C# syntax to declare the getter-only auto-property ? Opt. 1 - public int Property1 => 42; Opt. 2 - public int Property2 { get => 42; } Opt. 3 - public int Property3 { get { return 42; }
  • 26. A. All options are correct D. I’m Java developer What is the correct C# syntax to declare the getter-only auto-property ? Opt. 1 - public int Property1 => 42; Opt. 2 - public int Property2 { get => 42; } Opt. 3 - public int Property3 { get { return 42; }
  • 28. Local Functions List<T> items, values values, • Value Type to build closure @ky7m #dotnet #fwdays
  • 30. Ref Returns ref ref ref ref place = 9; WriteLine(array[4]); // prints 9 @ky7m #dotnet #fwdays
  • 31. Tuples • New Tuples are value types @ky7m #dotnet #fwdays
  • 32. • Struct type • Not replace Task, but help to • drastically reduce the number of allocations • method inlining ValueTask<T> @ky7m #dotnet #fwdays
  • 33. The hardest problem in computer science is fighting the urge to solve a different, more interesting problem than the one at hand. Nick Lockwood
  • 34. • Exposes implementation details • Code Complexity • Obscures Logic • Missing Static Checks • More Exception Handlers • Security • Performance Problems with Reflection @ky7m #dotnet #fwdays
  • 35. • Available on Nuget - https://www.nuget.org/packages/FastMember • Open-source - https://github.com/mgravell/fast-member/ • Uses ILGenerator and SiteCall power FastMember @ky7m #dotnet #fwdays
  • 36. FastMember Example Usage var string // smth known at runtime while /* some loop of data */ // obj could be static or DLR var string // smth known at runtime @ky7m #dotnet #fwdays
  • 37. FastMember and SqlBulkCopy var new var @ky7m #dotnet #fwdays
  • 38. • Nuget - https://www.nuget.org/packages/System.Runtime.Co mpilerServices.Unsafe/ • Low-level functionality for manipulating pointers • Whole code is single IL file System.Runtime.CompilerServices.Unsafe @ky7m #dotnet #fwdays
  • 39. Unsafe class api public static class Unsafe // all methods are public static unsafe void void void value int object where class void ref value ref void void InitBlock void byte uint void CopyBlock void void uint ref void @ky7m #dotnet #fwdays
  • 40. With Unsafe you’re more Safe var 10 var ref //void* var int // int @ky7m #dotnet #fwdays
  • 41. • One Really Big Query Expression (60-line query) • A lot of LINQ To * (what you want) LINQ is fantastic feature of C#! @ky7m #dotnet #fwdays
  • 42. Even R# helps… @ky7m #dotnet #fwdays
  • 43. • Hidden allocations • Possible multiple enumeration • Easy to write a non-optimal query LINQ downsides @ky7m #dotnet #fwdays
  • 44. • Nuget - https://www.nuget.org/packages/LinqOptimizer.CSharp/ • Works at run-time • Requires AsQueryExpr().Run() to LINQ methods • Optimizes Parallel LINQ • Specialized strategies and algorithms LinqOptimizer @ky7m #dotnet #fwdays
  • 45. • https://github.com/antiufo/roslyn-linq-rewrite • Works at compile time (build step) • No code changes • No allocations for Expression<> trees and enumerator boxing • Parallel LINQ is not supported RoslynLinqRewrite @ky7m #dotnet #fwdays
  • 46. • https://github.com/dotnet/corefxlab/tree/master/src /System.Slices • Span is a simple struct that gives you uniform access to any kind of contiguous memory • 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. Span (Slice) @ky7m #dotnet #fwdays
  • 47. Make subslices without allocations byte stackalloc byte 256 var new byte 256 char new char ’ ' 'N' 'E' 'T' char new char char 0 4 @ky7m #dotnet #fwdays
  • 48. • Nuget - https://www.nuget.org/packages/System.Buffers/ • ArrayPool • resource pool that enables reusing instances of T[] • managed memory • NativeBufferPool (experimental, under corefxlab) • Unmanaged memory • pool of Slice<T> System.Buffers @ky7m #dotnet #fwdays
  • 49. • Get your own instance • ArrayPool<T>.Shared (Thread safe) • NativeBufferPool<byte>.SharedByteBufferPool (Thread safe) • ArrayPool<T>.Create(int maxArrayLength, ..) • Rent • Specify the min size • Bigger can be returned, don’t rely on .Length • Finally { Return } • Alternative - Microsoft.IO.RecyclableMemoryStream • Provide pooling for .NET MemoryStream objects • Limited usage How to work with Pools @ky7m #dotnet #fwdays
  • 50. • Heap allocation viewer Heap Allocations Viewer R# plugin Clr Heap Allocation Analyzer VS extension • Roslyn analyzers https://github.com/dotnet/roslyn-analyzers https://github.com/Wintellect/Wintellect.Analyzers https://github.com/DotNetAnalyzers/StyleCopAnalyzers • Annotations [StackOnly] - Microsoft.CodeAnalysis.StackOnlyTypes [NoAlloc] ensures a method doesn’t allocate [MustNotCopy] ensures a struct isn’t copied [Scoped] ensures a value doesn’t escape the callee ... and more ... Essential tools in your toolbox @ky7m #dotnet #fwdays
  • 51. • C# delivers productivity and safety, good performance from JIT to AOT and everything in between • A lot of features are “free” • Structs can improve memory performance • Less GC pressure • Better memory locality • Less overall space usage • Beware of copying large structs, “ref returns” • New features in next rev of C# and .NET: ValueTask, ValueTuple, others • Use power of Roslyn Summary
  • 52. • https://github.com/dotnet/corefx • https://github.com/dotnet/coreclr • https://github.com/dotnet/corefxlab • https://github.com/dotnet/roslyn • https://github.com/dotnet/corert • https://github.com/dotnet/coreclr/blob/master/Doc umentation/botr/readytorun-overview.md Links
  • 53. Questions @ky7m | ifesenko.com | ifesen@softserveinc.com

Notas do Editor

  1. SIMD – Single instruction Multiply Data
  2. https://github.com/mattwarren/GCVisualisation