SlideShare a Scribd company logo
High
Performanc
e Coding
with .NET
Core and C#
Shyma’a Qadoom..☺
ASP
.NET Core
Performance Best
Practices
Understand hot code paths
a hot code path is defined as a code
path that is frequently called and where
much of the execution time occurs. Hot
code paths typically limit app scale-out
and performance.
Avoid blocking calls
ASP
.NET Core apps should be designed to process
many requests simultaneously. Asynchronous APIs
allow a small pool of threads to handle thousands of
concurrent requests by not waiting on blocking calls.
Rather than waiting on a long-running synchronous
task to complete, the thread can work on another
request.
A common performance problem in ASP
.NET Core
apps is blocking calls that could be asynchronous.
Many synchronous blocking calls lead to degraded
response times.
 Make hot code paths asynchronous.
 Call data access, I/O, and long-running operations APIs asynchronously if an
asynchronous API is available. Do not use Task.Run to make a synchronous
API asynchronous.
 Make controller/Razor Page actions asynchronous. The entire call stack is
asynchronous in order to benefit from async/await patterns.
 A profiler, such as PerfView, can be used to find threads frequently added
to the Thread Pool.
Return large collections across multiple
smaller pages
A webpage shouldn't load large amounts of data all at once.
When returning A collection of objects, consider whether it could
lead to performance issues. Determine if the design could
produce the following poor outcomes:
Outofmemoryexception or high memory consumption
Slow response times
Frequent garbage collection
Do add pagination to mitigate the preceding scenarios. Using
page size and page index parameters, developers should favor
the design of returning A partial result. When an exhaustive result
is required, pagination should be used to asynchronously
populate batches of results to avoid locking server resources.
Return IEnumerable<T> or IAsyncEnu
merable<T>
Returning IEnumerable<T> from an action results in synchronous
collection iteration by the serializer. The result is the blocking of calls and a
potential for thread pool starvation. To avoid synchronous enumeration,
use ToListAsync before returning the enumerable.
Beginning with ASP
.NET Core 3.0, IAsyncEnumerable<T> can be used as
an alternative to IEnumerable<T> that enumerates asynchronously.
Minimize large object allocations
The .NET Core garbage collector manages allocation and
release of memory automatically in ASP
.NET Core apps.
Automatic garbage collection generally means that developers
don't need to worry about how or when memory is freed.
However, cleaning up unreferenced objects takes CPU time, so
developers should minimize allocating objects in hot code paths.
Garbage collection is especially expensive on large objects (> 85
K bytes). Large objects are stored on the large object heap and
require a full (generation 2) garbage collection to clean up.
Frequent allocation and de-allocation of large objects can
cause inconsistent performance.
Recommendations:
Do consider caching large objects that are frequently used.
Caching large objects prevents expensive allocations.
Do pool buffers by using an ArrayPool<T> to store large arrays.
Do not allocate many, short-lived large objects on hot code
paths.
Memory issues, such as the preceding, can be diagnosed by
reviewing garbage collection (GC) stats in PerfView and examining:
Garbage collection pause time.
What percentage of the processor time is spent in garbage
collection.
Optimize data access and I/O
Interactions with a data store and other remote
services are often the slowest parts of an ASP
.NET
Core app. Reading and writing data efficiently is critical
for good performance.
Recommendations:
Do call all data access APIs asynchronously.
Do not retrieve more data than is necessary. Write queries to return just the data that's necessary for the
current HTTP request.
Do consider caching frequently accessed data retrieved from a database or remote service if slightly out-of-
date data is acceptable. Depending on the scenario, use a MemoryCache or a DistributedCache.
Do minimize network round trips. The goal is to retrieve the required data in a single call rather than several
calls.
Do use no-tracking queries in Entity Framework Core when accessing data for read-only purposes. EF Core can
return the results of no-tracking queries more efficiently.
Recommendations:
Do filter and aggregate LINQ queries (with .Where, .Select, or .Sum statements, for example) so that the filtering
is performed by the database.
Do consider that EF Core resolves some query operators on the client, which may lead to inefficient query
execution.
Do not use projection queries on collections, which can result in executing "N + 1" SQL queries.
We recommend measuring the impact of the preceding high-performance approaches before committing the
base. The additional complexity of compiled queries may not justify the performance improvement.
Query issues can be detected by reviewing the time spent accessing data with Application Insights or with
tools. Most databases also make statistics available concerning frequently executed queries.
Minify client assets
ASP
.NET Core apps with complex front-ends frequently serve many JavaScript,
CSS, or image files. Performance of initial load requests can be improved by:
Bundling, which combines multiple files into one.
Minifying, which reduces the size of files by removing whitespace and
comments.
Recommendation: Do consider other third-party tools, such as Webpack, for
complex client asset management.
Minimize exceptions
Exceptions should be rare. Throwing and catching exceptions is slow
relative to other code flow patterns. Because of this, exceptions shouldn't be
used to control normal program flow.
Recommendations:
Do not use throwing or catching exceptions as a means of normal program
flow, especially in hot code paths.
Do include logic in the app to detect and handle conditions that would
cause an exception.
Do throw or catch exceptions for unusual or unexpected conditions.
App diagnostic tools, such as Application Insights, can help to identify
common exceptions in an app that may affect performance.
Performance and reliability
The following sections provide performance tips and
known reliability problems and solutions.
Do not store
IHttpContextAccessor.HttpCont
ext in a field
Do not do this: The following
example stores
the HttpContext in a field and
then attempts to use it later.
The preceding code frequently
captures a null or
incorrect HttpContext in the
constructor.
Do this: The following example:
Stores
the IHttpContextAccessor in a
field.
Uses the HttpContext field at
the correct time and checks
for null.
Do not use the
HttpContext after the
request is complete
HttpContext is only valid as long as there is
an active HTTP request in the ASP
.NET Core
pipeline. The entire ASP
.NET Core pipeline is
an asynchronous chain of delegates that
executes every request. When
the Task returned from this chain completes,
the HttpContext is recycled.
Do not do this: The following example
uses async void which makes the HTTP
request complete when the first await is
reached:
Which is ALWAYS a bad practice in ASP
.NET
Core apps.
Accesses the HttpResponse after the HTTP
request is complete.
Crashes the process.
Do this: The following example
returns a Task to the framework,
so the HTTP request doesn't
complete until the action
completes.
Do not capture the
HttpContext in
background threads
Do not do this: The following
example shows a closure is
capturing the HttpContext from
the Controller property. This is a
bad practice because the work
item could:
Run outside of the request
scope.
Attempt to read the
wrong HttpContext.
Do this: The following example:
Copies the data required in the
background task during the
request.
Doesn't reference anything
the controller.
Do not capture services
injected into the controllers on
background threads
Do not do this: The following
example shows a closure is
capturing the DbContext from
the Controller action parameter.
This is a bad practice. The work
item could run outside of the
request scope.
The ContosoDbContext is scoped
to the request, resulting in
an ObjectDisposedException.
Do this: The following example:
Injects an IServiceScopeFactory in
order to create a scope in the
background work item.
IServiceScopeFactory is a singleton.
Creates a new dependency injection
scope in the background thread.
Doesn't reference anything from the
controller.
Doesn't capture the
ContosoDbContext from the incoming
request.
Performance Diagnostic Tools
in Visual Studio for .NET Core –
PerfTips and Profiler
PerfTips
“Typical” way of measuring code performance in
development: StopWatch – or worse: DateTime.Now
Visual Studio (since VS 2015) does it automatically with
breakpoints and PerfTips
Performance Profiler – For .NET Core
 Sampling Profiler
 Tracking memory allocations
 Unfortunately the Instrumentation Profiler does not support .NET Core in the current VS Version (15.3.2)
Demo
Have a nice day
Thank you

More Related Content

Similar to High Performance Coding2.pptx

Web Speed And Scalability
Web Speed And ScalabilityWeb Speed And Scalability
Web Speed And Scalability
Jason Ragsdale
 
Presemtation Tier Optimizations
Presemtation Tier OptimizationsPresemtation Tier Optimizations
Presemtation Tier Optimizations
Anup Hariharan Nair
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
Bishnu Rawal
 
Clug 2011 March web server optimisation
Clug 2011 March  web server optimisationClug 2011 March  web server optimisation
Clug 2011 March web server optimisation
grooverdan
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011
rob_dimarco
 
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Black Friday and Cyber Monday- Best Practices for Your E-Commerce DatabaseBlack Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Tim Vaillancourt
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
Anand Gupta
 
Tips and Tricks For Faster Asp.NET and MVC Applications
Tips and Tricks For Faster Asp.NET and MVC ApplicationsTips and Tricks For Faster Asp.NET and MVC Applications
Tips and Tricks For Faster Asp.NET and MVC Applications
Sarvesh Kushwaha
 
Assignment #2 Lab Exercise – HTTP INT6143, Enterpr.docx
Assignment #2 Lab Exercise – HTTP   INT6143, Enterpr.docxAssignment #2 Lab Exercise – HTTP   INT6143, Enterpr.docx
Assignment #2 Lab Exercise – HTTP INT6143, Enterpr.docx
davezstarr61655
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
Akhil Mittal
 
Asynchronous reading and writing http r equest
Asynchronous reading and writing http r equestAsynchronous reading and writing http r equest
Asynchronous reading and writing http r equest
Pragyanshis Patnaik
 
Best practices android_2010
Best practices android_2010Best practices android_2010
Best practices android_2010
Sunil Bhatia (Certified Scrum Master)
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
Matthias Noback
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
kaven yan
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
rudib
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
Naveen Kumar Veligeti
 
scale_perf_best_practices
scale_perf_best_practicesscale_perf_best_practices
scale_perf_best_practices
webuploader
 
Headless approach for offloading heavy tasks in Magento
Headless approach for offloading heavy tasks in MagentoHeadless approach for offloading heavy tasks in Magento
Headless approach for offloading heavy tasks in Magento
Sander Mangel
 
ASP.NET Best Practices - Useful Tips from the Trenches
ASP.NET Best Practices - Useful Tips from the TrenchesASP.NET Best Practices - Useful Tips from the Trenches
ASP.NET Best Practices - Useful Tips from the Trenches
Habeeb Rushdan
 

Similar to High Performance Coding2.pptx (20)

Web Speed And Scalability
Web Speed And ScalabilityWeb Speed And Scalability
Web Speed And Scalability
 
Presemtation Tier Optimizations
Presemtation Tier OptimizationsPresemtation Tier Optimizations
Presemtation Tier Optimizations
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
Clug 2011 March web server optimisation
Clug 2011 March  web server optimisationClug 2011 March  web server optimisation
Clug 2011 March web server optimisation
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011
 
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Black Friday and Cyber Monday- Best Practices for Your E-Commerce DatabaseBlack Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Tips and Tricks For Faster Asp.NET and MVC Applications
Tips and Tricks For Faster Asp.NET and MVC ApplicationsTips and Tricks For Faster Asp.NET and MVC Applications
Tips and Tricks For Faster Asp.NET and MVC Applications
 
Assignment #2 Lab Exercise – HTTP INT6143, Enterpr.docx
Assignment #2 Lab Exercise – HTTP   INT6143, Enterpr.docxAssignment #2 Lab Exercise – HTTP   INT6143, Enterpr.docx
Assignment #2 Lab Exercise – HTTP INT6143, Enterpr.docx
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Asynchronous reading and writing http r equest
Asynchronous reading and writing http r equestAsynchronous reading and writing http r equest
Asynchronous reading and writing http r equest
 
Best practices android_2010
Best practices android_2010Best practices android_2010
Best practices android_2010
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
scale_perf_best_practices
scale_perf_best_practicesscale_perf_best_practices
scale_perf_best_practices
 
Headless approach for offloading heavy tasks in Magento
Headless approach for offloading heavy tasks in MagentoHeadless approach for offloading heavy tasks in Magento
Headless approach for offloading heavy tasks in Magento
 
ASP.NET Best Practices - Useful Tips from the Trenches
ASP.NET Best Practices - Useful Tips from the TrenchesASP.NET Best Practices - Useful Tips from the Trenches
ASP.NET Best Practices - Useful Tips from the Trenches
 

Recently uploaded

National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

High Performance Coding2.pptx

  • 1. High Performanc e Coding with .NET Core and C# Shyma’a Qadoom..☺
  • 2. ASP .NET Core Performance Best Practices Understand hot code paths a hot code path is defined as a code path that is frequently called and where much of the execution time occurs. Hot code paths typically limit app scale-out and performance.
  • 3. Avoid blocking calls ASP .NET Core apps should be designed to process many requests simultaneously. Asynchronous APIs allow a small pool of threads to handle thousands of concurrent requests by not waiting on blocking calls. Rather than waiting on a long-running synchronous task to complete, the thread can work on another request. A common performance problem in ASP .NET Core apps is blocking calls that could be asynchronous. Many synchronous blocking calls lead to degraded response times.
  • 4.  Make hot code paths asynchronous.  Call data access, I/O, and long-running operations APIs asynchronously if an asynchronous API is available. Do not use Task.Run to make a synchronous API asynchronous.  Make controller/Razor Page actions asynchronous. The entire call stack is asynchronous in order to benefit from async/await patterns.  A profiler, such as PerfView, can be used to find threads frequently added to the Thread Pool.
  • 5. Return large collections across multiple smaller pages A webpage shouldn't load large amounts of data all at once. When returning A collection of objects, consider whether it could lead to performance issues. Determine if the design could produce the following poor outcomes: Outofmemoryexception or high memory consumption Slow response times Frequent garbage collection Do add pagination to mitigate the preceding scenarios. Using page size and page index parameters, developers should favor the design of returning A partial result. When an exhaustive result is required, pagination should be used to asynchronously populate batches of results to avoid locking server resources.
  • 6. Return IEnumerable<T> or IAsyncEnu merable<T> Returning IEnumerable<T> from an action results in synchronous collection iteration by the serializer. The result is the blocking of calls and a potential for thread pool starvation. To avoid synchronous enumeration, use ToListAsync before returning the enumerable. Beginning with ASP .NET Core 3.0, IAsyncEnumerable<T> can be used as an alternative to IEnumerable<T> that enumerates asynchronously.
  • 7. Minimize large object allocations The .NET Core garbage collector manages allocation and release of memory automatically in ASP .NET Core apps. Automatic garbage collection generally means that developers don't need to worry about how or when memory is freed. However, cleaning up unreferenced objects takes CPU time, so developers should minimize allocating objects in hot code paths. Garbage collection is especially expensive on large objects (> 85 K bytes). Large objects are stored on the large object heap and require a full (generation 2) garbage collection to clean up. Frequent allocation and de-allocation of large objects can cause inconsistent performance.
  • 8. Recommendations: Do consider caching large objects that are frequently used. Caching large objects prevents expensive allocations. Do pool buffers by using an ArrayPool<T> to store large arrays. Do not allocate many, short-lived large objects on hot code paths. Memory issues, such as the preceding, can be diagnosed by reviewing garbage collection (GC) stats in PerfView and examining: Garbage collection pause time. What percentage of the processor time is spent in garbage collection.
  • 9. Optimize data access and I/O Interactions with a data store and other remote services are often the slowest parts of an ASP .NET Core app. Reading and writing data efficiently is critical for good performance.
  • 10. Recommendations: Do call all data access APIs asynchronously. Do not retrieve more data than is necessary. Write queries to return just the data that's necessary for the current HTTP request. Do consider caching frequently accessed data retrieved from a database or remote service if slightly out-of- date data is acceptable. Depending on the scenario, use a MemoryCache or a DistributedCache. Do minimize network round trips. The goal is to retrieve the required data in a single call rather than several calls. Do use no-tracking queries in Entity Framework Core when accessing data for read-only purposes. EF Core can return the results of no-tracking queries more efficiently.
  • 11. Recommendations: Do filter and aggregate LINQ queries (with .Where, .Select, or .Sum statements, for example) so that the filtering is performed by the database. Do consider that EF Core resolves some query operators on the client, which may lead to inefficient query execution. Do not use projection queries on collections, which can result in executing "N + 1" SQL queries. We recommend measuring the impact of the preceding high-performance approaches before committing the base. The additional complexity of compiled queries may not justify the performance improvement. Query issues can be detected by reviewing the time spent accessing data with Application Insights or with tools. Most databases also make statistics available concerning frequently executed queries.
  • 12. Minify client assets ASP .NET Core apps with complex front-ends frequently serve many JavaScript, CSS, or image files. Performance of initial load requests can be improved by: Bundling, which combines multiple files into one. Minifying, which reduces the size of files by removing whitespace and comments. Recommendation: Do consider other third-party tools, such as Webpack, for complex client asset management.
  • 13. Minimize exceptions Exceptions should be rare. Throwing and catching exceptions is slow relative to other code flow patterns. Because of this, exceptions shouldn't be used to control normal program flow. Recommendations: Do not use throwing or catching exceptions as a means of normal program flow, especially in hot code paths. Do include logic in the app to detect and handle conditions that would cause an exception. Do throw or catch exceptions for unusual or unexpected conditions. App diagnostic tools, such as Application Insights, can help to identify common exceptions in an app that may affect performance.
  • 14. Performance and reliability The following sections provide performance tips and known reliability problems and solutions.
  • 15. Do not store IHttpContextAccessor.HttpCont ext in a field Do not do this: The following example stores the HttpContext in a field and then attempts to use it later.
  • 16. The preceding code frequently captures a null or incorrect HttpContext in the constructor. Do this: The following example: Stores the IHttpContextAccessor in a field. Uses the HttpContext field at the correct time and checks for null.
  • 17. Do not use the HttpContext after the request is complete HttpContext is only valid as long as there is an active HTTP request in the ASP .NET Core pipeline. The entire ASP .NET Core pipeline is an asynchronous chain of delegates that executes every request. When the Task returned from this chain completes, the HttpContext is recycled. Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached: Which is ALWAYS a bad practice in ASP .NET Core apps. Accesses the HttpResponse after the HTTP request is complete. Crashes the process.
  • 18. Do this: The following example returns a Task to the framework, so the HTTP request doesn't complete until the action completes.
  • 19. Do not capture the HttpContext in background threads Do not do this: The following example shows a closure is capturing the HttpContext from the Controller property. This is a bad practice because the work item could: Run outside of the request scope. Attempt to read the wrong HttpContext.
  • 20. Do this: The following example: Copies the data required in the background task during the request. Doesn't reference anything the controller.
  • 21. Do not capture services injected into the controllers on background threads Do not do this: The following example shows a closure is capturing the DbContext from the Controller action parameter. This is a bad practice. The work item could run outside of the request scope. The ContosoDbContext is scoped to the request, resulting in an ObjectDisposedException.
  • 22. Do this: The following example: Injects an IServiceScopeFactory in order to create a scope in the background work item. IServiceScopeFactory is a singleton. Creates a new dependency injection scope in the background thread. Doesn't reference anything from the controller. Doesn't capture the ContosoDbContext from the incoming request.
  • 23. Performance Diagnostic Tools in Visual Studio for .NET Core – PerfTips and Profiler
  • 24. PerfTips “Typical” way of measuring code performance in development: StopWatch – or worse: DateTime.Now Visual Studio (since VS 2015) does it automatically with breakpoints and PerfTips
  • 25. Performance Profiler – For .NET Core  Sampling Profiler  Tracking memory allocations  Unfortunately the Instrumentation Profiler does not support .NET Core in the current VS Version (15.3.2)
  • 26. Demo
  • 27. Have a nice day Thank you