Tuesday, February 10, 2009

Improving Performance Of a website

Tips
1) Implement Serverside ViewState


If you think your website is running slowly and you need to improve performance by 150% in short time. This may help you a lot.

ASP.NET ViewState is a great mechanism that simplifies the life of ASP.NET developers. But, as everybody knows, the .NET Framework saves the ViewState data as a hidden field on your ASPX page. If your page has only a few controls, this is not a problem. But, if your page has some Panels and/or some DataGrids, with the technique demonstrated on this article, you could reduce dramatically the load time of the page.

We will start our analysis thinking where the Framework needs to work with the data saved on the ViewState hidden field. The answer is: only on the server side. The system doesn't need to work with the ViewState data on the client side, so, if we start to save this data on the server instead of carrying all this from the server to the client and from the client to the server again, we will save a lot of time while loading our documents. You probably won't note the difference while loading the page on the same computer that the application is installed, but, test it using a dial-up connection and you will see what happens. You could also see the size of the source code generated with and without this technique.

You can store ViewState in Cache, Session or Database. I have attached sample code for implementing this idea in your application.

All that you need to do is add a reference to the class that accompanies this example and inherit your "code-behind files" from it instead of the System.Web.UI.Page, and add the Config information to your Web.Config.

For more help please visit:
http://www.codeproject.com/KB/viewstate/ServerViewState.aspx

If you are storing ViewState in Session and if you are continuously receiving the following error even after you set ViewStateTableSize to 200, you should store your ViewState to Database, because after that increasing it more would not help more in improving performance:
"VIEWStateKey not Found. Consider increasing the ViewStateTableSize parameter on Web.Config file."

2) Use Gzip Compression

For more help please visit:


http://www.dotnetjunkies.com/Article/16267D49-4C6E-4063-AB12-853761D31E66.dcik

When you are editing MetaBase.xml, make sure the section of GZip looks like the following:






3) Create Application Pool and Increase worker processes



If your website is using DefaultApplicationPool, then you need to create separate application poll for your website in IIS and you and increase worker processes from 1 to 5 or 10 depending on Server’s configuration. But when you will increase worker processes it will create environment like web garden and your session and static variables won’t work, so you will have think for some other alternatives for those variables.

Steps to implement this:


























4) Enable Catching Images in IIS

One of the simplest but most effective methods of to improve performance is to cache images on the client.

For more help please visit:
http://www.dotnetjunkies.com/Article/16267D49-4C6E-4063-AB12-853761D31E66.dcik

















5) Load only necessary parts

Sometimes it happens that there are lots of controls on one page, but user is not looking at it on first sight. Just look at the picture below:
















There are 8 hidden pages in this screen, whenever user click on any tab, only then that part is loaded, otherwise it is not loaded. I have kept all 8 pages in Iframe and it reduced page load time to 50%.

6) Some General Tips:

If you still need something and save your each millisecond, there are other lots of tricks:

• In web.config Turn off Tracing unless until required.
• In web.config Turn off session state in web.config file or at least for a page if there are no
sessions.
• In web.config set debug=false
• In web.config Increase the Pool "Packet size" for transferring large blob or image fields
For more help please visit:

http://www.codeproject.com/KB/aspnet/Application_Performance.aspx
http://www.developer.com/net/article.php/3711321

8.1.Avoid Server-Side Validation:

Try to avoid server-side validation, use client-side instead. Server-Side will just consume valuable resources on your servers, and cause more chat back and forth.

8.2.Repeater Control Good, DataList, DataGrid, and DataView controls Bad

Asp.net is a great platform, unfortunately a lot of the controls that were developed are heavy in html, and create not the greatest scalable html from a performance standpoint. ASP.net repeater control is awesome! Use it! You might write more
code, but you will thank me in the long run!

8.3.Avoid Exceptions

Avoid throwing exceptions, and handling useless exceptions. Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications. Write your code so they don’t happen! Don’t code by exception!

8.4.Use the Finally Method

If you have opened any connections to the database, or files, etc, make sure that you close them at the end! The Finally block is really the best place to do so, as it is the only block of code that will surely execute

8.5.Always check Page.IsValid when using Validator Controls

So you’ve dropped on some validator controls, and you think your good to go because ASP.net does everything for you! Right?
Wrong! All that happens if bad data is received is the IsValid flag is set to false. So make sure you check Page.IsValid
before processing your forms!

8.6.StringBuilder

StringBuilder.Append is faster than String + String. However in order to use StringBuilder, you must
new StringBuilder()
Therefore it is not something you want to use if you don’t have large strings. If you are concatenating less than 3 times,
then stick with String + String. You can also try String.Concat.

8.7.Efficient Coding Practices

Avoid late binding whenever possible. Late-binding adds flexibility but is always slow compared to early binding. Note that
using virtual methods in your code requires late binding, because virtual methods must be mapped. Any class that contains a virtual method has its own virtual table. The virtual table in turn contains entries that correspond to the virtual methods
that the class contains. Note that the virtual method is class specific; there can be only one virtual table per class
regardless of how many virtual methods the class contains. The runtime uses the virtual table to map a virtual method to the
object on which it is called. Hence there's additional overhead involved (more resource usage—both processor and memory) in
binding a virtual method to the object on which it is called to satisfy a virtual method call.

8.8.Choosing between Server.Transfer and Response.Redirect

Use the Server.Transfer method to redirect between pages in the same application; Server.Transfer avoids an unnecessary client-side redirection. However, you cannot always just replace Response.Redirect calls with Server.Transfer. If you need authentication and authorization checks during redirection, use Response.Redirect instead. The two mechanisms are not equivalent. When you use Response.Redirect, make sure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised. Also note that you can only use Server.Transfer to transfer control to pages within the same application. To transfer to pages in other applications, you must use
Response.Redirect.

9.9.Use Paging

Take advantage of paging’s simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster.
Just be careful when you mix in caching. How many times do you hit the page 2, or page 3 button? Hardly ever right! So don’t cache all the data in the grid! Think of it this way: How big would the first search result page be for “music” on Google if they cached all the pages from 1 to goggle.

8.10.Encoding

By default ASP.NET applications use UTF-8 encoding. If your application is using ASCII codes only, it is preferred to set
your encoding to ASCII to improve your application performance.

8.11.Authentication

It is recommended to turn authentication off when you do not need it. The authentication mode for ASP.NET applications is windows mode. In many cases it is preferred to turn off the authentication in the 'machin.config' file located on your server and to enable it only for applications that really need it.

8.12.Debug Mode

Before deploying your web application you have to disable the debug mode. This makes your deployed application faster than before. You can disable or enable debug mode form within your application's 'web.config' file under the 'system.web' section
as a property to the 'compilation' item. You can set it to 'true' or 'false'.

8.13.Garbage Collector

ASP.NET provides automatic garbage collection and memory management. The garbage collector's main task is to allocate and release memory for your application. There are some tips you can take care of when you writing your application's code to
make the garbage collector works for your benefit:
Avoid using objects with a Finalize sub as possible and avoid freeing resources in Finalize functions.
Avoid allocating too much memory per web page because the garbage collector will have to do more work for each request and
this increases CPU utilization (not to mention you can go out of memories in larger web applications)
Avoid having unnecessary pointers to objects because this makes these objects alive until you free them yourself within your code not in an automatic way.

8.15.Use "ArrayLists" in place of arrays

How it improves performance
An ArrayList as everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList interface.

8.16. Avoid using unmanaged code

How it affects performance:
Calls to unmanaged code are a costly marshaling operation.
Solution:
Try to reduce the number calls between the managed and unmanaged code. Consider to do more work in each call rather than making frequent calls to do small tasks.

8.17.Threading

If your application contains some operation that consumes time and resources, then instead of blocking the application flow


8.18.Precompilation

When an already deployed ASP.NET web application page is requested for the first time, that page needs to be compiled (by the server) before the user gets a response. The compiled page or code is then cached so that we need not to compile it again for the coming requests. It is clear that the first user gets a slow response than the following users. This scenario is repeated for each web page and code file within your web site.
When using precompilation then the ASP.NET entire web application pages and code files will be compiled ahead. So, when a user requests a page from this web application he will get it in a reasonable response time whatever he is the first user or not.
Precompiling the entire web application before making it available to users provides faster response times. This is very useful on frequently updated large web applications.

8.19.Data Access

The following points give you some ideas about how to render data access efficient:
Use SQL server provider
Among the data providers available to be used, choose SQL data provider to build a high performance, scalable web application.
Use SQL Data Reader
The SQLDataReader class gives you the ability to read only retrieved records from the database for once. So, if this is all what you actually need, then it is extremely recommended to use a data reader class instead of a DataSet or, a Table Class.
This will gives your application much higher performance.


Make use of SQLDataSource useful properties
Instead of writing a query that includes the "Where", or "Sort By" clauses use the caching, filtering, and sorting properties of the SQLDataSourse provider. You can set the SQLDataSource object's "EnableCaching" property to true to enable caching of the retrieved data by this data source. When you enable data source caching, SQLDataSource will do the operations like filtering and sorting on the cached data. You can use the "FilterExpression" property, and the "SortParameterName" property to perform filtering and sorting using the SQLDataSource object. This will certainly makes your application faster.

8.20.SessionState State

Disable session state when you are not using it. Not all web application require a session state for each user. When you disable unneeded session state you are definitely improving your application performance.
To disable session state for a complete page in your application, use the following code:
<%@ page EnableSessionState="false" %>
If your page requires access to session variables only to read them then set the session state for this page to read only.
To disable session state for the entire application, open the 'web.config' file, and set the mode attribute to off under the
session state section as in the following code:

Session State Provider
There are more than one approach for storing your session state data. You can choose the approach you prefer by setting the mode attribute under the session state section of your application 'web.config' file. The supported modes are: in-process mode, state server mode, SQL server mode, and custom mode. Each mode is suitable in some circumstance, and has its own set of advantages. The in-process session state is by far the fastest one. So, it is recommended to use the in-process provider if

you want to store small amounts of volatile data in the session state. Other state server and SQL server providers are needed if your application using a web farm or garden, or if you want to retain your session state date if the web server is restarted

8.21.Security Considerations

Constrain unwanted Web server traffic.
Turn off authentication for anonymous access.
Validate user input on the client.
Avoid per-request impersonation.
Avoid caching sensitive data.
Segregate secure and non-secure content.
Only use Secure Sockets Layer (SSL) for pages that require it.
Use absolute URLs for navigation.
Consider using SSL hardware to offload SSL processing.
Tune SSL timeout to avoid SSL session expiration.

8.22 Deployment Considerations

Avoid unnecessary process hops.
Understand the performance implications of a remote middle tier.
Short-circuit the HTTP pipeline.
Configure the memory limit.
Disable tracing and debugging.
Ensure content updates do not cause additional assemblies to be loaded.
Avoid XCOPY under heavy load.
Consider precompiling pages.
Consider Web garden configuration.
Consider using HTTP compression.
Consider using perimeter caching.
8.23 Design Considerations
Design your data access layer based on how the data is used.
Cache data to avoid unnecessary work.
Connect by using service accounts.
Acquire late, release early.
Close disposable resources.
Reduce round trips.
Return only the data you need.
Use Windows authentication.
Choose the appropriate transaction type.
Use stored procedures.
Prioritize performance, maintainability, and productivity when you choose how to pass data across layers.
Consider how to handle exceptions.
Use appropriate normalization.

8.23 ADO.Net Considerations

Microsoft .NET Framework Data Providers:
Use System.Data.SqlClient for Microsoft SQL Server™ 7.0 and later.
Use System.Data.OleDb for SQL Server 6.5 or OLE DB providers.
Use System.Data.ODBC for ODBC data sources.
Use System.Data.OracleClient for Oracle.
Use SQLXML managed classes for XML data and SQL Server 2000.



Connections:
Open and close the connection in the method.
Explicitly close connections.
When using DataReaders, specify CommandBehavior.CloseConnection.
Do not explicitly open a connection if you use Fill or Update for a single operation.
Avoid checking the State property of OleDbConnection.
Pool connections.
Commands:
Validate SQL input and use Parameter objects.
Retrieve only the columns and rows you need.
Support paging over large result sets.
Batch SQL statements to reduce round trips.
Use ExecuteNonQuery for commands that do not return data.
Use ExecuteScalar to return single values.
Use CommandBehavior.SequentialAccess for very wide rows or for rows with binary large objects (BLOBs).
Do not use CommandBuilder at run time.
Stored Procedures:
Use stored procedures.
Use CommandType.Text with OleDbCommand.
Use CommandType.StoredProcedure with SqlCommand.
Consider using Command.Prepare.
Use output parameters where possible.
Consider SET NOCOUNT ON for SQL Server.


Parameters:
Use the Parameters collection when you call a stored procedure.
Use the Parameters collection when you build SQL statements.
Explicitly create stored procedure parameters.
Specify parameter types.
Cache stored procedure SqlParameter objects.
DataReader:
Close DataReader objects.
Consider using CommandBehavior.CloseConnection to close connections.
Cancel pending data.
Consider using CommandBehavior.SequentialAccess with ExecuteReader.
Use GetOrdinal when using an index-based lookup.
DataSet:
Reduce serialization.
Use primary keys and Rows.Find for indexed searching.
Use a DataView for repetitive non-primary key searches.
Use the optimistic concurrency model for datasets.
XML and DataSet Objects:
Do not infer schemas at run time.
Perform bulk updates and inserts by using OpenXML.
Transactions:
Use SQL transactions for server controlled-transactions on a single data store.
Use ADO.NET transactions for client-controlled transactions on a single data store.
Use Distributed Transaction Coordinators (DTC) for transactions that span multiple data stores.

Keep transactions as short as possible.
Use the appropriate isolation level.
Avoid code that can lead to deadlock.
Set the connection string Enlist property to false.

8.25 Optimize Expensive Loops

Expensive loops in any application can cause performance problems. To reduce the overhead that is associated with code inside
loops, you should follow these recommendations:
Avoid repetitive field or property access.
Optimize code inside the loop.
Copy frequently called code into the loop.
Replace recursion with looping.
Use For instead of ForEach in performance-critical code paths.

8.26 Implement a Global.asax Error Handler

The first step in managing exceptions is to implement a global error handler in the Global.asax file or in the code-behind file. Implementing a global error handler traps all unhandled exceptions in your application. Inside the handler, you should,
at a minimum, log the following information to a data store such as a database, the Windows event log, or a log file:









Table of Contents

Performance tools for ASP.NET
1. Red Gate Profiler

Features :

* Profile any .NET language. It doesn't matter whether you're programming in C#, VB.NET, managed C++, or in COBOL.NET. If you're programming for the .NET Framework, then ANTS Profiler can help you.

* web applications so you can identify slow code in your .NET websites and web services. ANTS Profiler will identify slow-loading pages and, more importantly, tell you why they are slow.

* Profiling Windows Forms applications so you can optimize rich, client-side applications.

* Profile .NET 3.0 applications – WCF (Indigo), WPF (Avalon), WF, XBAP.

* Profile web applications on IIS 5, IIS 5.1, IIS 6, IIS 7, and ASP.NET Development Web Server (Cassini).

* Integration with Visual Studio 2003 and Visual Studio 2005, so you can starting profiling your
application from within your IDE. A click of a button launches ANTS Profiler within seconds, with the executable path already set. Context sensitivity lets you set up what method, class or namespace you want to profile, without having to remember its name.

* Fast mode performance profiling to speed up identifying bottlenecks in complex code, also performs inlining to really understand how your code performs.

* memory to understand how your application uses memory.

* that allows fine-grained control of the profiler when profiling your code.

* Support for 64-bit profiling on x64 processors.

Table of Contents

2. .NET Memory Profiler

.NET Memory Profiler is a powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language.

.NET Memory Profiler will help you to

* View real-time memory and resource information
The profiler presents real-time information about all .NET instance allocations performed on the garbage collected heap and all instances that reside on the heap.

* identify memory leaks by collecting and comparing snapshots of .NET memory
Snapshots include data about the .NET instance allocations and live instances at the time the snapshot was collected. They provide a lot of useful information and make it easy to identify potential memory leaks, especially when two snapshots are compared.

* Find instances that are not properly disposed
The profiler also contains a dispose tracker, which provides additional data about disposable instances (i.e. instances of classes implementing the System.IDisposable interface).

* Get detailed information about unmanaged resource usage
The unmanaged resources tracker can collect detailed information about unmanaged resources (such as HWND, HBITMAP and unmanaged memory) and present it together with the .NET memory information.

* Optimize memory usage
The heap-utilization tracker will tell you how the managed heaps are used. Together with the real-time view and the dispose tracker this information can be used to optimize the memory usage of the application.

* Investigate memory problems in production code
Profiling memory problems in production code is greatly simplified by using the "attach to process" feature and the possibility to import memory dump files.

* Perform automated memory testing
The .NET Memory Profiler API makes it possible to automatically detect memory leaks and control the profiler from within the profiled program.

* Retrieve information about native memory
In addition to presenting information about the GC heap and unmanaged resources, the profiler also presents information about the native memory of the profiled process or any other process running on the computer.

Table of Contents

3. dotTrace Profiler

1. Performance profiling
dotTrace provides an extremely fast way to profile the performance of .NET applications (frameworks 1.x, 2.0 or 3.x).

Features:

* Convenient data representation
A number of informative views (Call Tree, Hot Spots and more) allow convenient inspection of profiling data stored in snapshots. The importance of each function call is represented with descriptive icons, along with precise execution times and other relevant information. You can open functions in individual tabs, easily navigate views with keyboard shortcuts, skip through unimportant or filtered calls, and create profiling reports by saving any view to an external file.

* Versatile profiling modes
dotTrace offers two additional performance profiling modes: Sampling profiling (vs. Tracing profiling) and Routine thread time measurement (vs. Wall time measurement). A total of 4 possible profiling modes are now available.

profiling is a profiling method which is up to 30 times faster than regular tracing profiling, but at the expense of lower accuracy. It is extremely useful for at least two profiling scenarios: first, quickly getting a general idea of your application's performance, and second, profiling for extensive periods of time, up to many hours long.

* thread time is measured by a thread-specific timer which is paused when its thread is paused. Using this mode, dotTrace can measure the contribution of individual threads in multithreaded applications, reducing interference between threads.

* Performance snapshot comparison
dotTrace is able to compare any two performance snapshots of the same application. It generates a comparison snapshot which shows the difference in the number of calls and times consumed by each function. Comparison snapshots can be viewed and analyzed the same way as regular performance snapshots.

* Quick Info
You can look up Quick Info on any function from the Call Tree view. The lookup window provides a summary of function statistics with respect to the selected call and to all calls in the current tab.

* Filtering
You can apply predefined and customizable filter patterns to focus on the functions most important to you. Filter out system calls and other nonessential functions with a combination of different Hide filters. Emphasize specific functions of selected classes with one or more Show filters.

* Folding and advanced filtering

dotTrace makes it much easier to see all the data you want to see and none that you don't.

• Fold filtered calls
Chains of filtered calls can be set to be folded by default or folded/unfolded manually.

• Fold recursive calls
Recursive call chains can be folded to display the aggregate timings and call counts of all functions called recursively.

• Hide functions with 0% of root time
Functions that consumed 0% of root time can be hidden from view.

* function
Quickly locate functions and navigate to them. Optimize the way you like to search: type in the function name or use the provided list of namespaces and classes to go through the hierarchy.

You can highlight all occurrences of the function in the current view and then navigate between them with a simple press of a key. You can also quickly open the function in a new tab, or view its Quick Info.

* Tab saving
Individual tabs in performance snapshots may be saved as separate snapshots.

2. Memory profiling
With dotTrace you can quickly profile the memory usage of your .NET applications (frameworks 2.0 and 3.x only). The profiling process is not only simple but fast. A wealth of profiling data is accurately recorded and presented in the form of memory snapshots, allowing thorough analysis of memory issues.

* Versatile memory profiling modes
Depending on your needs, you can profile memory in two different ways:

• To check what objects are currently loaded in memory (but shouldn't be), you can dump memory at any time during profiling.

• To also view the difference between two application memory states, during profiling you can mark the start and the end of a time interval, then capture a snapshot containing the difference data. A difference snapshot lets you see how much new memory was allocated and how much was released during the marked time interval. The view can be filtered to show only Live objects, only New objects, only Dead objects, only Garbage objects, or the difference between New and Dead objects.

* data representation

• Each memory snapshot holds a wealth of data on all objects allocated in memory, from the roots to every single object allocated or deleted at any time during the profiling session.

• A number of views are available to you for examining and analyzing memory snapshots, including Class List, Namespace Tree, Outgoing references, Shortest root path, and Allocation Tree. You can also focus on any subsystem of your application by opening it in a separate tab.

* Find objects by class
To help you locate the presence of particular class of objects in memory, dotTrace provides the rapid Find objects by class (Ctrl+N) search feature. The use of wildcards and CamelCase abbreviations is supported for faster search results.

* Finalized objects
dotTrace lets you see finalized objects — objects which were deleted by the finalizer. You can examine them to find that some were not properly disposed of in the code of your application, which is a potential memory leak.

* Merging strongly-connected objects
When you are navigating though the graph of objects in memory, some dependencies are difficult to see at a glance. dotTrace offers an easy way to merge (group) strongly-connected objects together, so that you can see which objects and/or groups any particular node is holding.

3. General Features

* profiling
dotTrace decisively outperforms its in-class competitors. This fact alone ensures that you save valuable time with its profiling speed and ease of use.

* Source view
dotTrace automatically locates the underlying source code for selected functions. If necessary, you can manually specify the appropriate source code location by browsing to the source files.

* If your solution is currently opened, click the quick link in Source View to navigate to the corresponding source file in Visual Studio.

* can also configure source lookup to make sure dotTrace looks in the right place for source files. Define folder substitutions in case your code has been moved, or to allow your development team to see the same snapshots and view the source code correctly.

* Multiple snapshots
dotTrace easily handles multiple snapshots, providing you with all-around profiling convenience. First, you can generate an unlimited number of snapshots of the same application during a single profiling session. Second, you can open several snapshots at the same time, so that you can compare and contrast them (for performance snapshots, this can even be done automatically).

* Profiling ASP.NET applications
dotTrace easily profiles ASP.NET applications running on IIS, versions 5.x, 6.0 and 7.0, and/or on Visual Studio Development web-server. Simply specify the start page URL of your web application and profile it the same way as a desktop program. ASP.NET applications can also be profiled from Visual Studio.

* Windows services profiling
dotTrace lets you easily profile Windows services. Just select the service from the list of all available Windows services and profile it the same way as web applications.

* with Visual Studio

* dotTrace from Visual Studio — with the click of the button you can profile the StartUp project of your solution in Visual Studio. In addition, if you have the JetBrains ReSharper add-in installed on your Visual Studio, you can easily start profiling unit tests from the code editor.
* Open a file from dotTrace in Visual Studio — if your solution is opened in Visual Studio, you can click a quick link in Source View to navigate to the corresponding source file in Visual Studio.

* Command line options
You can profile applications, open snapshots and generate reports from any batch script by using the command line options provided with dotTrace.

* Profiling API
Use advanced profiling scenarios by controlling profiling functions from within the application being profiled, with the help of our Profiling API.

Table of Contents

4. NeoLoad
NeoLoad is the load testing software designed to test Web applications.

• An intelligent and intuitive interface makes testing easy.
• Analysis using integrated, advanced performance monitors.
• No scripting - even with the most complex scenarios.
• Supports all Web and Web 2.0 standards.
• A range of services, training and advices are available to assist you.



No comments: