0% found this document useful (0 votes)
4 views11 pages

SP Optimization and .Net Tips

The document provides optimization tips for stored procedures and ASP.NET Core applications, emphasizing the use of stored procedures to reduce network traffic and enhance security, as well as the importance of asynchronous programming to improve application performance. Key recommendations include avoiding synchronous calls, using caching, optimizing data access, and employing Entity Framework Core query optimizations. Additional suggestions focus on breaking down large procedures, minimizing temporary tables, and ensuring efficient exception handling to enhance overall application performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

SP Optimization and .Net Tips

The document provides optimization tips for stored procedures and ASP.NET Core applications, emphasizing the use of stored procedures to reduce network traffic and enhance security, as well as the importance of asynchronous programming to improve application performance. Key recommendations include avoiding synchronous calls, using caching, optimizing data access, and employing Entity Framework Core query optimizations. Additional suggestions focus on breaking down large procedures, minimizing temporary tables, and ensuring efficient exception handling to enhance overall application performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Stored Procedures Optimization Tips

 Use stored procedures instead of heavy-duty queries.


This can reduce network traffic, because your client will send to server
only stored procedure name (perhaps with some parameters) instead of
large heavy-duty queries text. Stored procedures can be used to enhance
security and conceal underlying data objects also. For example, you can
give the users permission to execute the stored procedure to work with
the restricted set of the columns and data.

 Include the SET NOCOUNT ON statement into your stored


procedures to stop the message indicating the number of rows
affected by a Transact-SQL statement.
This can reduce network traffic, because your client will not receive the
message indicating the number of rows affected by a Transact-SQL
statement.
 Call stored procedure using its fully qualified name.
The complete name of an object consists of four identifiers: the server
name, database name, owner name, and object name. An object name
that specifies all four parts is known as a fully qualified name. Using fully
qualified names eliminates any confusion about which stored procedure
you want to run and can boost performance because SQL Server has a
better chance to reuse the stored procedures execution plans if they were
executed using fully qualified names.
 Consider returning the integer value as an RETURN statement
instead of an integer value as part of a recordset.
The RETURN statement exits unconditionally from a stored procedure, so
the statements following RETURN are not executed. Though the RETURN
statement is generally used for error checking, you can use this
statement to return an integer value for any other reason. Using RETURN
statement can boost performance because SQL Server will not create a
recordset.
 Don't use the prefix "sp_" in the stored procedure name if you
need to create a stored procedure to run in a database other than
the master database.
The prefix "sp_" is used in the system stored procedures names. Microsoft
does not recommend to use the prefix "sp_" in the user-created stored
procedure name, because SQL Server always looks for a stored procedure
beginning with "sp_" in the following order: the master database, the
stored procedure based on the fully qualified name provided, the stored
procedure using dbo as the owner, if one is not specified. So, when you
have the stored procedure with the prefix "sp_" in the database other
than master, the master database is always checked first, and if the user-
created stored procedure has the same name as a system stored
procedure, the user-created stored procedure will never be executed.
 Use the sp_executesql stored procedure instead of the EXECUTE
statement.
The sp_executesql stored procedure supports parameters. So, using the
sp_executesql stored procedure instead of the EXECUTE statement
improve readability of your code when there are many parameters are
used. When you use the sp_executesql stored procedure to executes a
Transact-SQL statements that will be reused many times, the SQL Server
query optimizer will reuse the execution plan it generates for the first
execution when the change in parameter values to the statement is the
only variation.
 Use sp_executesql stored procedure instead of temporary stored
procedures.
Microsoft recommends to use the temporary stored procedures when
connecting to earlier versions of SQL Server that do not support the reuse
of execution plans. Applications connecting to SQL Server 7.0 or SQL
Server 2000 should use the sp_executesql system stored procedure
instead of temporary stored procedures to have a better chance to reuse
the execution plans.
 If you have a very large stored procedure, try to break down this
stored procedure into several sub-procedures, and call them from
a controlling stored procedure.
The stored procedure will be recompiled when any structural changes
were made to a table or view referenced by the stored procedure (for
example, ALTER TABLE statement), or when a large number of INSERTS,
UPDATES or DELETES are made to a table referenced by a stored
procedure. So, if you break down a very large stored procedure into
several sub-procedures, you get chance that only a single sub-procedure
will be recompiled, but other sub-procedures will not.
 Try to avoid using temporary tables inside your stored procedure.
Using temporary tables inside stored procedure reduces the chance to
reuse the execution plan.
 Try to avoid using DDL (Data Definition Language) statements
inside your stored procedure.
Using DDL statements inside stored procedure reduces the chance to
reuse the execution plan.
 Add the WITH RECOMPILE option to the CREATE PROCEDURE
statement if you know that your query will vary each time it is
run from the stored procedure.
The WITH RECOMPILE option prevents reusing the stored procedure
execution plan, so SQL Server does not cache a plan for this procedure
and the procedure is recompiled at run time. Using the WITH RECOMPILE
option can boost performance if your query will vary each time it is run
from the stored procedure because in this case the wrong execution plan
will not be used.
 Use SQL Server Profiler to determine which stored procedures
has been recompiled too often.
To check the stored procedure has been recompiled, run SQL Server
Profiler and choose to trace the event in the "Stored Procedures" category
called "SP:Recompile". You can also trace the event "SP:StmtStarting" to
see at what point in the procedure it is being recompiled. When you
identify these stored procedures, you can take some correction actions to
reduce or eliminate the excessive recompilations.

1. Always Use ASP.NET Core Latest


Version
The first version of ASP.NET Core was released in 2016 with Visual Studio 2015 and now
we have ASP.NET Core 2.2 version available. If you compare the performance
improvement from the first version to the current version, you will find that the
application developed in ASP.NET Core 2.2 (current latest version) runs very fast
compared to the previous version. Microsoft always brings some performance
improvement in the next version compared to the previous version.

So, while creating the application using ASP.NET Core, always prefer to use the latest
version of ASP.NET Core. With the latest version, you will definitely find the performance
improvement. Next version of ASP.NET Core is 3.0 which is under development and
hopefully, it will be released very soon with Visual Studio 2019.

2. Avoid Synchronous Call in any


Level
While developing the ASP.NET Core application, just try to avoid creating blocking calls.
Blocking call means a call that blocks the next execution until it will not be completed.
Blocking call or synchronous call can be anything, either you are fetching the data from
API or performing some operations internally. You should always execute the call in an
asynchronous manner.
3. Always Use Asynchronous
Programming (Async-Await)
Asynchronous programming model was introduced in C# 5.0 and became very popular.
ASP.NET Core uses the same Asynchronous Programming paradigm to make an
application more reliable, faster and responsiveness.

You should use end to end Asynchronous Programming while writing the code. Let’s
take one example, we have one ASP.NET Core MVC application with database
implementation. As we know, it could have many separations and it all depends on user
project architecture, but take some simple example where we
have Controller > Repository Layer, etc. Let's see how you will write the sample
code at the controller level.
C#
Copy Code

[HttpGet]
[Route("GetPosts")]
public async Task < IActionResult > GetPosts()
{
try {
var posts = await postRepository.GetPosts();
if (posts == null) {
return NotFound();
}

return Ok(posts);
}
catch (Exception) {
return BadRequest();
}
}

This is how we implement asynchronous programming at the repository level.

C#
Copy Code

public async Task < List < PostViewModel >> GetPosts()


{
if (db != null) {
return await(from p in db.Post
from c in db.Category
where p.CategoryId == c.Id
select new PostViewModel
{
PostId = p.PostId,
Title = p.Title,
Description = p.Description,
CategoryId = p.CategoryId,
CategoryName = c.Name,
CreatedDate = p.CreatedDate
}).ToListAsync();
}

return null;
}

4. Avoid Task.Wait or Task.Result


with Asynchronous Programming
While working with Asynchronous Programming, we recommended you avoid
using Task.Wait and Task.Result and try to use await because of the following
reason:
1. These block the thread until the task completed and wait for completion of the
task. Waitblock the thread synchronously until the task completes.
2. Wait and Task.Result both wrap any type of exception
in AggregateException and create the complexity while doing exception
handling. If you use the await instead of Task.Wait and Task.Result, then
you don’t have to worry about exception handling.
3. Sometimes, these both block the current thread and create DEADLOCKS.
4. Wait and Task.Result can only be used if parallel task execution is going on.
We recommend that don’t use it with Async programming.
Let's understand a good and bad example of Task.Wait as follows:
C#
Copy Code

// Good Performance
Task task = DoWork();
await task;

// Bad Performance
Task task = DoWork();
task.Wait();
Let's understand a good and bad example of Task.Result as follows:
C#
Copy Code

// Good Performance on UI
Task < string > task = GetEmployeeName();
txtEmployeeName.Text = await task;

// Bad Performance on UI
Task < string > task = GetEmployeeName();
txtEmployeeName.Text = task.Result;
Know more about Best Practices for Asynchronous Programming.

5. Perform I/O Operations


Asynchronously
While performing I/O operations, you should perform it asynchronously without affecting
the other processes. I/O operations mean, doing some execution with a file like
uploading or retrieving files. It could be anything like image uploading, file uploading or
anything else. If you try to accomplish it in a synchronous manner, then it blocks the
main thread and stops the other background execution till the I/O completes. So, from
the performance point of view, you should always use the Asynchronous execution for
I/O operations.

We have lots of Async methods available for I/O operations


like ReadAsync, WriteAsync, FlushAysnc, etc. Here is one simple example how we
can create a copy of one file asynchronously.
C#
Copy Code

public async void CreateCopyOfFile()


{
string dir = @"c:\Mukesh\files\";

using(StreamReader objStreamReader = File.OpenText(dir + "test.txt"))


{
using(StreamWriter objStreamWriter = File.CreateText(dir +
"copy_test.txt"))
{
await CopyFileToTarget(objStreamReader, objStreamWriter);
}
}
}

public async Task CopyFileToTarget(StreamReader objStreamReader, StreamWriter


objStreamWriter)
{
int num;
char[] buffer = new char[0x1000];

while ((num = await objStreamReader.ReadAsync(buffer, 0, buffer.Length)) !=


0) {
await objStreamWriter.WriteAsync(buffer, 0, num);
}
}
6. Always Use Cache
We can increase the performance of the application if we can reduce the number of the
request to the server every time. It does not mean that you will not make the call to the
server, it only means that you will not make the call to server every time. First time, you
will make the call to the server and get the response and this response is stored
somewhere for future perspective for some time (there will be some expiry) and next
time, when you will make the call for the same response, then first, you will check that if
you have already got data in the first request and stored somewhere and if it is yes,
then you will use the stored data rather than making the call to the server.

Keeping the data in that location from where we can get it frequently without making
the call to the server is a good practice. Here, we can use the Cache. Caching the
content helps us to reduce server calls again and again and it helps us to increase the
performance of the application. We can do the cache at any point of a location like on
client-side caching, server-side caching or client/server-side caching.
We have different kinds of caching available in ASP.NET Core like we can do the caching
In-Memory or we can use Response caching or we can use Distributed Caching. More
about Caching in Asp.Net Core.
C#
Copy Code

public async Task < IActionResult > GetCacheData()


{
var cacheEntry = await
_cache.GetOrCreateAsync(CacheKeys.Entry, entry => {
entry.SlidingExpiration = TimeSpan.FromSeconds(120);
return Task.FromResult(DateTime.Now);
});

return View("Cache", cacheEntry);


}

7. Optimize Data Access


We can also improve the performance of the application to optimize the data access
logic. As we all know, most of the application is totally dependent on the database and
every time, we have to fetch the data from a database and need to show on UI. If it is
time-consuming, then the application will take much time to load. Here, we have a few
techniques which can be implemented while doing the code which can improve the
performance much better.

1. Reduce the number of HTTP calls, means you should always try to reduce the
number of network round trips.
2. Try to get all the data in one go. Means rather than making multiple calls to the
server, just make one or two calls which can bring all required data.
3. Frequently, set the cache on data which is not being changed.
4. Don’t try to get the data in advance which is not required, it will increase the
load on the response and your application will load slower.

8. Optimize Custom Code


Apart from optimizing the data access logic, we can also optimize the business logic or
middleware custom code. Optimizing or refactoring these codes help us to improve the
performance of the applications. Here, we have some points on which we should focus.

1. Custom Logging, Authentication or some custom handler code which executes on


every request should be optimized.
2. Don’t perform custom long-running custom execution in the business logic layer
or middleware, it basically blocks the request to go to the server and application
takes much time to get the data. You should have optimized code for this, either
at the client side or database side.
3. Always check that a long-running task should be performed asynchronously
without affecting other processes.
4. You can take real-time client-server communication example as SignalR which
works asynchronously.

9. Entity Framework Core Query


Optimization
As we all know, EF Core is an ORM for .NET developers which helps us to play with
database object without writing much code as usual. It helps us to use a database using
Models. Data access logic code can play a vital role in performances. If your code is not
optimized, then your application will not perform well.

But if you write your data access logic in optimize ways in EF Core, then definitely it
improves the performance of the application. Here, we have some of the techniques
which will increase the performance.

1. Use No Tracking while getting the data which is the only read-only purpose. It
improves performance.
2. Try to filter the data on the database side, don’t fetch the whole data using query
and then filter at your end. You can use some function available in EF Core
like Where, Select which help you to filter the data on the database side.
3. Retrieve only the required number of records which is necessary using the help
of Take and Skip. You can take one example of paging where you can
implement Take and Skip while clicking on the page number.

Let's take one example and try to understand how we can optimize the EF Core
query using Select and AsNoTracking.
C#
Copy Code
public async Task < PaginatedList < Post >> GetPagedPendingPosts
(int pageIndex, int pageSize, List<Category> allowedCategories)
{
var allowedCatIds = allowedCategories.Select(x => x.Id);
var query = _context.Post
.Include(x => x.Topic.Category)
.Include(x => x.User)
.Where(x => x.Pending == true &&
allowedCatIds.Contains(x.Topic.Category.Id))
.OrderBy(x => x.DateCreated);

return await PaginatedList<Post>.CreateAsync(query.AsNoTracking(),


pageIndex, pageSize);
}

10. Some Other Tips


Here, we have some other performance improvement stuff which can be implemented
in ASP.NET Core application.

1. Write logic in such a way for the process which is optimized and tested and which
minimizes the exception to be a part of the flow. Less number of chances to
execute the exception code means high performed application.
2. Always try to use simple NET code or highly performed ORM like Dapper for
database operations. It is because if database operations will take much time to
execute the query, then it will decrease the performance of the application. As
we all know, in the development phase, implementing the ADO.NET code and
managing it will take more time as compared to ORM implementation. But this is
also true if you use simple ADO.NET, then your application will be faster than if
you use any other ORM.
3. If response size is large, than obviously it will take much time to load it. So,
always reduce the response size using compression techniques and then load the
data. You can implement the compression logic in middleware. We have some of
the compression providers like Gzip, Brotli.
C#
Copy Code

public void ConfigureServices(IServiceCollection services)


{
services.AddResponseCompression();

services.Configure<GzipCompressionProviderOptions>(options => {
options.Level = CompressionLevel.Fastest;
});
}
Bonus Tips (Client Side)
We would like to share some of the performance tips for client-side code. If you are
creating a website using the ASP.NET Core MVC, then I believe you should always follow
these tips to make your website perform well.

 Bundling and Minification

Using bundling and minification, we can optimize the content before loading on
UI. From the performance point of view, always try to load all your client-side
assets like JS/CSS in one go. It reduces the number of network hits. You can first
minify your files using minification and then bundle those in one file which can be
loaded faster and reduce the number of an HTTP request for resources.

 Load JavaScript at Last

You should always try to load your JavaScript files at last. We have many benefits
like first of all, your website gets rendered in minimum time and when your
JavaScript will execute, then your DOM elements will be available. Using this, you
can make your application faster.

 Shrink Images

Always avoid loading images in maximum size. Before loading, you can shrink
the images using compression techniques.

 Use CDN

If you have your custom CSS or JavaScript files, then it’s OK to load it. But if you
are using some third party libraries which have CDN version available, then
always try to use the CDN file path rather than downloaded library file path from
your end. It is because CDN has different servers available on a different zone, if
you are using a website in one zone, then you will get the CDN file from your
zone server when you hit the website, which is very fast.

Edit code and continue Debugging


in Visual Studio (C#, VB, C++)
5
Is this page helpful?

Edit and Continue is a time-saving feature that enables you to make changes
to your source code while your program is in break mode. When you resume
execution of the program by choosing an execution command
like Continue or Step, Edit and Continue automatically applies the code
changes with some limitations. This allows you to make changes to your
code during a debugging session, instead of having to stop, recompile your
entire program, and restart the debugging session.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy