Best Practices For asp.net Development

Spread the love

This article suggests a few tips to improve the performance of an ASP.NET application. There are many more things which may ensure a better performance and faster response time for a web application.Here we are discussing only a few of the best practices that will help you avoid some unwanted performance hitters from your application. So, you will have a more lightweight application which runs quicker and gives a better response time. In this article, we tried to highlight the key tips you can use to maximize the performance of your ASP.NET pages.

1. Plan and research before you develop

Research and investigate how .NET can really benefit you. .NET offers a variety of solutions on each level of application design and development. It is imperative that you understand your situation and pros and cons of each approach supported by this rich development environment. Visual Studio is a comprehensive development package and offers many options to implement the same logic. It is really important that you examine each option and find the best optimal solution suited for the task at hand. Use layering to logically partition your application logic into a presentation, business, and data access layers. It will not only help you create maintainable code but also permits you to monitor and optimize the performance of each layer separately. A clear logical separation also offers more choices for scaling your application. Try to reduce the amount of code in your code-behind files to improve maintenance and scalability.

2. Use Caching

Caching is a good technique to improve your application’s performance. If your application has infrequent data changes or the application has more static content of web page, you can use caching. If your application does not mandate near real-time content to be delivered, consider using output caching. But, the data won’t be the latest for the duration mentioned while enabling caching.

When using caching, what it does is – it stores the content on IIS. So, the subsequent requests for the page are loaded immediately from the IIS for the certain period.

You can cache entire page or fragments of pages or controls depending on the type of static data you have.

3. Disable View State if Possible

View State is a technique used by an ASP.NET to persist changes to the state of a web form across postbacks to retain the current data for a web application which is otherwise stateless. But View State increases the load of the page both when requested and served. There is also an additional overhead of serializing and de-serializing view state data as it is posted back. View State increases the memory allocations on the server as well.

We can disable the View State of the pages where there is no postback required. This is applicable for controls as well. By default, View State is turned on for all pages and controls. So, turn it off for a page or a control wherever it is not required.

  • Disable view state for a single page,
    <%@ Page EnableViewState="false" %>

  • Disable view state for a single control on a page,
    Set EnableViewState = “false”

    Set debug=false

When you create the application, debug attribute will be set to “true” by default since it is very useful during development. But, always set debug=”false” before deployment. This is a very small thing you need to do but will have a greater impact on the application performance.

4. Use session variables carefully

Avoid storing too much data in session variables, and make sure your session timeout is reasonable. This can use a significant amount of server memory. Keep in mind that data stored in session variables can hang out long after the user closes the browser. Too many session variables can bring the server to its knees. Disable session state, if you are not using session variables in the particular page or application.

  • To disable session state for a page, set the EnableSessionState attribute in the
    @Page directive to false.i.e.

    <%@ Page EnableSessionState="false" %>

  • If a page requires access to session variables but will not create or modify them, set the EnableSessionState attribute in the@ Page directive to ReadOnly. i.e.

    <%@ Page EnableSessionState="ReadOnly" %>

  • To disable session state for a specific application, use the following element in the Web.config file of the application.

  • To disable session state for all applications on your Web server, use the following element in the Machine.config file:

  • Determine the size of your ViewState

    By enabling tracing for the page, you can monitor the ViewState size for each control. You can use this information to determine the optimal size of the ViewState or if there are controls in which the ViewState can be disabled.

5. Avoid Unnecessary Round Trips to Server

Round trips to server significantly affect performance. This is because the requests and responses are created and transferred to server and client. It also takes some time for the server to do the processing and object creation before the response is sent back. Adding to this, sometimes other factors, such as a server is busy with too many requests, network latency etc., can further affect the speed. So, keep round trips to an absolute minimum. How it can be done in each case may depend on your application. A few examples are:

  • Use Ajax UI whenever possible
  • Do user input validation on the client side using JavaScript
  • Avoid unnecessary database hits to load the unchanged content in the database
  • Use IsPostBack method effectively

6. Use Specific CSS and Script files

Using large CSS files that are used for the entire site in multiple pages will increase the loading time of the page thus leading to a performance hit. It can be split and stored in different files thus loading only what is required for each page. It will minimize the loading time of the pages. For example,

contactus.css can be used for ContactUs.aspx and home.css can be used for Home.aspx, The same way you can split your JavaScript files as well.

7. Use Paging

Take advantage of paging’s simplicity in .net. Loading a large number of records into the server data controls like GridView, DataGrid, and ListView etc. will take a lot of time for the page to load. But, if we show only small subsets of data at a time, the page will load faster. On click of Next button, Previous button or on the page number, you can load another page.

8. Use String builder to concatenate strings

Use String instead of StringBuilder when you must modify or concatenate a string several times. A string is immutable while StringBuilder is mutable. You cannot change immutable objects after it was created. Any operation that intended to change it, will return a new instance.

For example, the following code creates 2003 instances of string object.

    string numbers = “{“; // Creates one instance.
    for (int counter = 0; counter < 100; counter++)
    {

      numbers += counter.ToString() + “, “; // Creates 2 instance for a loop; one for counter.ToString() and one for numbers.

    }
    numbers = numbers.Trim(‘,’, ‘ ‘); // Creates another instance.
    numbers += “}”; // Creates another instance.

    While the following code with StringBuilder puts much less stress on memory allocator:
    StringBuilder numbers = new StringBuilder(“{“); // Creates one instance.

    for (int counter = 0; counter < 100; counter++)
    {

      numbers.Append(counter);
      numbers.Append(“, “);

    }

    numbers = numbers.Remove(numbers.Length – 2, 2);
    numbers.Append(“}”);

This didn’t mean to say it is bad to use Strings, it is useful in may circumstances. For example, instances of immutable types are inherently thread-safe, since no thread can modify it. Just avoid using them when you modify it several times.

9. Use Server.Transfer instead of Response.Redirect for any transfers within your server

Both Server.Transer and Response.Redirect present the user with the contents of a new page but in different ways. When we use Response.Redirect, the server sends an HTTP header back to the browser with an HTTP status code stating that the address of the object has changed along with the new location to find it. The browser then initiates another request to the new object.

On the other hand, Server.Transfer just transfers execution from one page to another page on the server. In effect, back-and-forth network traffic is reduced which therefore eases the pressure on your Web server and network bandwidth and makes your applications run faster.

10. Use Threads

Threading can help an application run faster, provided you handle it with care. Otherwise, it may cause more problems for you.

You can consider using processor intensive operations and IO operations in a background worker process, or in a separate thread. While one thread running one operation, another thread can work on another operation. This will make your application more responsive.

Now, we have multi-core processors available but many applications are not exploiting the benefits of them. Starting from .NET 4.0, we can use Task Parallel Library to exploit the benefits of parallelism.

11. Make your page asynchronous

From .NET 4.5 onwards, we have async and await keywords available which helps write asynchronous code more easily. So, try to use the potential of it. We can write asynchronous methods when there are tasks that can be done asynchronously.

Suppose, a method makes an API call and other unrelated tasks. If you make the method asynchronous by adding an async keyword, after the API call is made, the method executes rest of the code and comebacks when the API result s ready.

12. Use Stored Procedures

Use Stored Procedures to avoid multiple database hits and get many things done on a single hit. Also, there is a slight performance benefit for the stored procedure over queries as Store Procedures are compiled and stored in the SQL database server, unlike the queries which require compilation.

13. Use Images Properly

Reduce the use of images as it will take more time to load and will cause the application to load slowly. Better use very small images in the sense that, ones with less size and get it repeated using CSS. If possible, remove some images and use CSS to give colors, shades, and styles.

14. Use CSS Layouts

Try to use CSS layouts instead of heavy server controls or HTML table elements. For example, we can use ‘div’ elements controlled by CSS to create a table and it will be lightweight and will be easier to manage.

15. Set build action to Release

Always remember to take the build in release mode instead of debugging mode. Since building mode adds a pdb file for each dll and this will cause your application size to increase and execution time to increase. This is because the debug information is checked before executing code in these assemblies.

16. Minimise the use of unmanaged Assemblies

Usage of unmanaged assemblies can be a costlier business at times. It is better to avoid the use of unmanaged DLL’s if possible. Since CLR has no control over the calls made to such assemblies and you will have to handle the memory clean up.

17. Be more diligent while declaring variables

You can avoid a lot of unnecessary memory allocation if you are a bit more cautious while declaring a variable. A few cases are,

  • Avoid the use of dynamic keyword if it is not necessary: Because dynamic types cause compiler and Dynamic Language Runtime (DLR) to do more work. This affects performance and it will be more obvious in case if they are used in loops.
  • Move variable declaration closer to usage: It is better because you’re limiting the scope of the declared variables. And if you declare them outside the loop, their scope will be broader, which means that it will take longer for the garbage collector to free the memory they hold.

18. Do Minification

In production use the minified versions of javascript and css files. For the free javascript and css libraries, they will provide a minimied version, just juse the min.js instead of .js. Minify even your custom js and css files before moving to production to reduce the size of the pages.

19. Do Bundling

Microsoft introduced bundling in ASP.NET 4.5 framework. It makes it easy to combine or bundle multiple files into a single file. A bundle may contain many files and a single request is enough to bring all the code in the bundled files. When you use bundling it also minifies the content by removing extra space.

The benefits we get is temendous with budling and minification. Please check the Microsoft docs for further details: https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification

Conclusion

The Internet is a ubiquitous network to which scores of people have access. Until now, there has not really been a way to use the Internet as a software platform. However, the technology is now in place to make that happen, and ASP.NET makes it that much easier to manage Web programming. ASP.NET keeps all the good features of classic ASP (in process performance, a well-established syntax, the ability to add executable blocks to your Web page) and improves on them (e.g., by providing a more granular HTTP request handling model, providing a compilation model for Web pages, and organizing the parts of a Web page into classes and making those classes available through the CLR type system). ASP.NET will undoubtedly be the tool of choice for most Web developers for the next five to ten years.

For more information about asp.net Development, please drop an email to info@oditeksolutions.com

What OdiTek offers

Certified Developers

Deep Industry Expertise

IP Rights Agreement -Source Codes to Customers, legal compliance

NDA – Legally binding non-disclosure terms

Compliance to Software Development Quality Standards

Product Development Excellence

Dedicated Project Manager (Not billed)

Proactive Tech Support-Round the Clock

Commitment to Schedule

High performance, Secure software design

Guranteed Cost Savings & Value Addition

Consistent Achiever of Customer Happiness

Refer our Skills page:

ASP.NET Development

As an ASP NET development company, we specialize in providing a solid, flexible, and proven platform to propel your business into the next generation of corporate growth and prosperity. ASP.NET (Active Server Pages .NET), an open-source framework developed by Microsoft, empowers developers in ASP NET...

Read More

Client Testimonials

If you need additional information or have project requirements, kindly drop an email to: info@oditeksolutions.com

Latest Insights

PyTorch Insights : Deep Learning with Python

Deep learning has become the cornerstone of artificial intelligence, revolutionizing industries with its ability to analyze vast amounts of data and uncover patterns. Deep learning...

Why PyTorch Developers Are Essential for Your AI Projects

PyTorch developers are transforming industries with their expertise in artificial intelligence (AI). Using the PyTorch framework, they craft innovative AI-driven applications that address complex business...

Tips and Tricks to Hire Rust Developer

Rust, known for its speed, safety, and concurrency, has emerged as a leading programming language for developing high-performance applications. Whether it's system-level programming, web development,...

PyTorch Frameworks: Redefining the Future of Deep Learning

PyTorch frameworks have become indispensable in the rapidly evolving world of artificial intelligence (AI) and machine learning, offering the perfect tools for creating innovative and...

× How can I help you?