Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title.  However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important.  Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.

The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-

protected void Page_Load(object sender, EventArgs e)
{

this.Page.Title = “My ASP.NET Blog”;

this.Page.MetaKeywords = “ASP.NET, Web Development, Blog, ASP.NET Blog”;

this.Page.MetaDescription = “This Blog contains posts related to ASP.NET and Web Development”;

}

The above code appends the following markup

<meta content=”ASP.NET, Web Development, Blog, ASP.NET Blog” />

<meta content=”This Blog contains posts related to ASP.NET and Web Development” />

And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind  will fill up the “content” part alone if the “name” tag is matching.

Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria.  So far, these were set statically in the HTML.  Now with Page Class level access, these can be set dynamically.

Advertisements

ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development.  There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.

For this post, we will examine some of the web form enhancements.  There are sure a lot of them and we will examine some of them in the future posts.

Controlling View State using the ViewStateMode Property – Performance Enhancement

One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance.  While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.

With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly.  Ex.-

<asp:Panel ID=”pnlViewState” runat=”server” ViewStateMode=”Disabled”>
Disabled: <asp:Label runat=”server”  Text=”Value set in markup” ViewStateMode=”Inherit” /><br />
Enabled: <asp:Label  runat=”server” Text=”Value set in markup” ViewStateMode=”Enabled” />
<hr />
<asp:button ID=”Button1″ runat=”server”  Text=”Postback” />
</asp:Panel>

In the code-behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
label1.Text = “Value set in code behind”;
label2.Text = “Value set in code behind”;
}
}

When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged.  As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled.  That is the reason label2 maintains viewstate while label1 loses it.

While it is arguably possible using the simple EnableViewState property earlier, it was never consistent.  Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

if(someVariableExists)
   x = false

However, consider this:

if(someVariableExists)
   x = false
   anotherFunctionCall();

One might think that the code above would be equivalent to:

if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}

Unfortunately, he’d be wrong. In reality, it means:

if(someVariableExists) {
   x = false;
}
anotherFunctionCall();

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

if(2 + 2 === 4) return 'nicely done';

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.

4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

“JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
– JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.

5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

Place JS at bottom

Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. Declare Variables Outside of the For Statement

When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

Bad

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the “container” element each time — highly inefficient!

Better

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

7. The Fastest Way to Build a String

Don’t always reach for your handy-dandy “for” statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) – this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
– James Padolsey, james.padolsey.com

8. Reduce Globals

“By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.”
– Douglas Crockford

var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name

Better

var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we’ve “reduced our footprint” to just the ridiculously named “DudeNameSpace” object.

9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can’t easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, “The majority of my viewers have JavaScript enabled, so I won’t worry about it.” However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you’ve done so, begin to progressively enhance your layout!

11. Don’t Pass a String to “SetInterval” or “SetTimeOut”

Consider the following code:

setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);

Not only is this code inefficient, but it also functions in the same way as the “eval” function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

setInterval(someFunction, 3000);

12. Don’t Use the “With” Statement

At first glance, “With” statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example…

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

— instead of —

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they “behave very badly when setting new members.” Instead, you should use var.

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the “new” constructor, like so:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the “bad practice” stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

var o = {};

“Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc.” – dyn-web.com

14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

var a = ['Joe','Plumber'];

“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford

15. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

Better

var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

…Should be rather self-explanatory. I doubt there’s any real speed improvements here, but it cleans up your code a bit.

17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

var someItem = 'some string'
function doSomething() {
  return 'something'
}

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

var someItem = 'some string';
function doSomething() {
  return 'something';
}

18. “For in” Statements

When looping through items in an object, you might find that you’ll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}

As referenced from JavaScript: The Good Parts, by Douglas Crockford.

19. Use Firebug’s “Timer” Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug’s “timer” feature to log the results.

function TimeTracker(){
 console.time("MyTimer");
 for(x=5000; x > 0; x--){}
 console.timeEnd("MyTimer");
}

20. Read, Read, Read…

While I’m a huge fan of web development blogs (like this one!), there really isn’t a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

Read them…multiple times. I still do!

21. Self-Executing Functions

Rather than calling a function, it’s quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding — especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery’s “each” method is great for looping, but using a native “for” statement will always be an ounce quicker.

23. Crockford’s JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you’ll gain access to a new JSON global object, which can then be used to parse your .json file.

 var response = JSON.parse(xhr.responseText);

 var container = document.getElementById('container');
 for(var i = 0, len = response.length; i < len; i++) {
   container.innerHTML += '
	
  • ' + response[i].name + ' : ' + response[i].email + '
  • '; }

    24. Remove “Language”

    Years ago, it wasn’t uncommon to find the “language” attribute within script tags.

    <script type="text/javascript" language="javascript">
    ...
    </script>

    However, this attribute has long since been deprecated; so leave it out.

    if it is helpful, plese dont forget to leave a comment.

    We usually use Singleton design pattern where only one object of a class is required. It is very simple and I try to explain it.

    public class MyClass

    {

    static MyClass myclass;

    // make constructor private

    // now you cannot make a direct instance of this class like:

    // MyClass obj=new MyClass() // it wount compile

    private MyClass()

    {

    }

    public static MyClass GetInstance()

    {

    lock (typeof(MyClass))

    {

    if (myclass == null)

    {

    myclass = new MyClass();

    }

    }

    return myclass;

    }

    //Destructor

    ~MyClass()

    {

    myclass = null;

    }

    }

    Concept behind this patteren is very simple, we create a static object of a class which remains in memory until destroyed by the destructor.when we try to make another object of this class our method will check the existing instance, if already exist then retun the existing object otherwise create a new object.

    Now call the static method using this line of codes

    MyClass obj=MyClass.GetInstance();

    if it is helpful, plese dont forget to leave a comment.

    Best Practices to Improve ASP.Net Web Application Performance.

    Performance tuning can be tricky. It’s especially tough in Internet-related projects with lots of components running around, like HTML client, HTTP network, Web server, middle-tier components, database components, resource-management components, TCP/IP networks, and database servers. Performance tuning depends on a lot of parameters and sometimes, by changing a single parameter, performance can increase drastically.

    Introduction
    This document lists out some tips for optimizing ASP.Net Web applications and many traps and pitfalls are discussed as follows :

    Tips For Web Application

    1) Turn off Tracing unless until required
    Tracing is one of the wonderful features which enable us to track the application’s trace and the sequences. However, again it is useful only for developers and you can set this to “false” unless you require to monitor the trace logging.
    How it affects performance:
    Enabling tracing adds performance overhead and might expose private information, so it should be enabled only while an application is being actively analyzed.
    Solution:
    When not needed, tracing can be turned off using
    <trace enabled=”false” requestLimit=”10” pageoutput=”false” traceMode=”SortByTime” localOnly=”true”>

    2) Turn off Session State, if not required
    One extremely powerful feature of ASP.NET is its ability to store session state for users, such as a shopping cart on an e-commerce site or a browser history.
    How it affects performance:
    Since ASP.NET Manages session state by default, you pay the cost in memory even if you don’t use it. I.e. whether you store your data in in-process or on state server or in a Sql Database, session state requires memory and it’s also time consuming when you store or retrieve data from it.
    Solution:
    You may not require session state when your pages are static or when you do not need to store information captured in the page.
    In such cases where you need not use session state, disable it on your web form using the directive,
    <@%Page EnableSessionState=”false”%>
    In case you use the session state only to retrieve data from it and not to update it, make the session state read only by using the directive,
    <@%Page EnableSessionState =”ReadOnly”%>

    3) Disable View State of a Page if possible
    View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page’s tree of controls.
    View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data.
    How it affects performance:
    There are a number of drawbacks to the use of view state,
    § however.
    It increases the total payload of the page both when served and
    § when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server.
    View
    § state increases the memory allocations on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed.
    Solution:
    Pages that do not have any server postback events can have the view state turned off.
    The default behavior of the ViewState property is enabled, but if you don’t need it, you can turn it off at the control or page level. Within a control, simply set the EnableViewState property to false, or set it globally within the page using this setting:
    <%@ Page EnableViewState=”false” %>
    If you turn view state off for a page or control, make sure you thoroughly test your pages to verify that they continue to function correctly.

    4) Set debug=false in web.config
    When you create the application, by default this attribute is set to “true” which is very useful while developing. However, when you are deploying your application, always set it to “false”.
    How it affects performance:
    Setting it to “true” requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.
    Solution:
    Therefore, always set debug=”false” before deployment.

    5) Avoid Response.Redirect
    Response.Redirect () method simply tells the browser to visit another page.
    How it affects performance:
    Redirects are also very chatty. They should only be used when you are transferring people to another physical web server.
    Solution:
    For any transfers within your server, use .transfer! You will save a lot of needless HTTP requests. Instead of telling the browser to redirect, it simply changes the “focus” on the Web server and transfers the request. This means you don’t get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

    Tradeoffs:
    “.transfer” process can§ work on only those sites running on the server. Only Response.Redirect can do that.
    Server.Transfer maintains the original URL in the
    § browser. This can really help streamline data entry techniques, although it may make for confusion when debugging
    5. A) To reduce CLR Exceptions count, Use Response.Redirect (“.aspx”, false) instead of response.redirect (“.aspx”).

    6) Use the String builder to concatenate string
    How it affects performance:
    String is Evil when you want to append and concatenate text to your string. All the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.
    i.e. When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive.
    Solution:
    Use String Builder when ever string concatenation is needed so that it only stores the value in the original string and no additional reference is created.

    7) Avoid throwing exceptions
    How it affects performance:
    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.
    Solution:
    You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

    8) Use Finally Method to kill resources
    The finally§ method gets executed independent of the outcome of the Block.
    Always use
    § the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.

    9) Use Client Side Scripts for validations
    User Input is Evil and it must be thoroughly validated before processing to avoid overhead and possible injections to your applications.
    How It improves performance:
    Client site validation can help reduce round trips that are required to process user’s request. In ASP.NET you can also use client side controls to validate user input. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.

    10) Avoid unnecessary round trips to the server
    How it affects performance:
    Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
    Solution:
    Keep round trips to an absolute minimum§
    § Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed

    11) Use Page.ISPostBack
    Make sure you don’t execute code needlessly. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is first time loaded and not in response to client postbacks.

    12) Include Return Statements with in the Function/Method
    How it improves performance
    Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn’t change the semantics of the code at all, and it can help you get more speed from your application.

    13) Use Foreach loop instead of For loop for String Iteration
    Foreach is far more readable, and in the future it will become as fast as a For loop for special cases like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not be worth it.

    14) Avoid Unnecessary Indirection
    How it affects performance:
    When you use byRef, you pass pointers instead of the actual object.
    Many times this makes sense (side-effecting functions, for example), but you don’t always need it. Passing pointers results in more indirection, which is slower than accessing a value that is on the stack.
    Solution:
    When you don’t need to go through the heap, it is best to avoid it there by avoiding indirection.

    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.
    Tradeoffs:
    The downside of an ArrayList is the need to cast objects upon retrieval.

    16) Always check Page.IsValid when using Validator Controls
    Always make sure you check Page.IsValid before processing your forms when using Validator Controls.

    17) 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.
    Tradeoffs:
    Just be careful when you mix in caching. Don’t cache all the data in the grid.

    18) Store your content by using caching
    How it improves performance:
    ASP.NET allows you to cache entire pages, fragment of pages or controls. You can cache also variable data by specifying the parameters that the data depends. By using caching you help ASP.NET engine to return data for repeated request for the same page much faster.
    When and Why Use Caching:
    A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.
    Good candidate to use caching is if you have infrequent chance of data or static content of web page.

    19) Use low cost authentication
    Authentication can also have an impact over the performance of your application. For example passport authentication is slower than form-base authentication which in here turn is slower than Windows authentication.

    20) Minimize the number of web server controls
    How it affects performance:
    The use of web server controls increases the response time of your application because they need time to be processed on the server side before they are rendered on the client side.
    Solution:
    One way to minimize the number of web server controls is to taking into consideration, the usage of HTML elements where they are suited, for example if you want to display static text.

    21) 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.

    22) Avoid making frequent calls across processes
    If you are working with distributed applications, this involves additional overhead negotiating network and application level protocols. In this case network speed can also be a bottleneck. Try to do as much work as possible in fewer calls over the network.

    23) Cleaning Up Style Sheets and Script Files
    A quick and easy way to improve your§ web application’s performance is by going back and cleaning up your CSS Style Sheets and Script Files of unnecessary code or old styles and functions. It is common for old styles and functions to still exist in your style sheets and script files during development cycles and when improvements are made to a website.
    Many websites use a single CSS Style Sheet or Script File for the
    § entire website. Sometimes, just going through these files and cleaning them up can improve the performance of your site by reducing the page size. If you are referencing images in your style sheet that are no longer used on your website, it’s a waste of performance to leave them in there and have them loaded each time the style sheet is loaded.
    Run a web page analyzer against pages in
    § your website so that you can see exactly what is being loaded and what takes the most time to load.

    24) Design with ValueTypes
    Use simple structs when you can, and when you don’t do a lot of boxing
    and unboxing.
    Tradeoffs:
    ValueTypes are far less flexible than Objects, and end up hurting performance if used incorrectly. You need to be very careful about when you treat them like objects. This adds extra boxing and unboxing overhead to your program, and can end up costing you more than it would if you had stuck with objects.

    25) Minimize assemblies
    Minimize the number of assemblies you use to keep your working set small. If you load an entire assembly just to use one method, you’re paying a tremendous cost for very little benefit. See if you can duplicate that method’s functionality using code that you already have loaded.

    26) Encode Using ASCII When You Don’t Need UTF
    By default, ASP.NET comes configured to encode requests and responses as UTF-8.
    If ASCII is all your application needs, eliminated the UTF overhead can give you back a few cycles. Note that this can only be done on a per-application basis.

    27) Avoid Recursive Functions / Nested Loops
    These are general things to adopt in any programming language, which consume lot of memory. Always avoid Nested Loops, Recursive functions, to improve performance.

    28) Minimize the Use of Format ()
    When you can, use toString () instead of format (). In most cases, it will provide you with the functionality you need, with much less overhead.

    29) Place StyleSheets into the Header
    Web developers who care about performance want browser to load whatever content it has as soon as possible. This fact is especially important for pages with a lot of content and for users with slow Internet connections. When the browser loads the page progressively the header, the logo, the navigation components serve as visual feedback for the user.
    When we place style sheets near the bottom part of the html, most browsers stop rendering to avoid redrawing elements of the page if their styles change thus decreasing the performance of the page. So, always place StyleSheets into the Header

    30) Put Scripts to the end of Document
    Unlike StyleSheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all StyleSheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames.
    So,always have scripts at the end of the document.

    31) Make JavaScript and CSS External
    Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number of HTTP requests thus improving the performance.

    Tips For Database Operations

    1) Return Multiple Resultsets
    The database code if has request paths that go to the database more than once then, these round-trips decreases the number of requests per second your application can serve.
    Solution:
    Return multiple resultsets in a single database request, so that you can cut the total time spent communicating with the database. You’ll be making your system more scalable, too, as you’ll cut down on the work the database server is doing managing requests.

    2) Connection Pooling and Object Pooling
    Connection pooling is a useful way to reuse connections for multiple requests, rather than paying the overhead of opening and closing a connection for each request. It’s done implicitly, but you get one pool per unique connection string. Make sure you call Close or Dispose on a connection as soon as possible. When pooling is enabled, calling Close or Dispose returns the connection to the pool instead of closing the underlying database connection.
    Account for the following issues when pooling is a part of your design:
    Share connections§
    Avoid per-user logons to the
    § database
    Do not vary connection strings
    §
    Do not cache connections
    §

    3) Use SqlDataReader Instead of Dataset wherever it is possible
    If you are reading a table sequentially you should use the DataReader rather than DataSet. DataReader object creates a read only stream of data that will increase your application performance because only one row is in memory at a time.

    4) Keep Your Datasets Lean
    Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.
    Therefore Only put the records you need into the dataset.

    5) Avoid Inefficient queries
    How it affects performance:
    Queries that process and then return more columns or rows than necessary, waste processing cycles that could best be used for servicing other requests.

    Cause of Inefficient queries:
    Too§ much data in your results is usually the result of inefficient queries.
    § The SELECT * query often causes this problem. You do not usually need to return all the columns in a row. Also, analyze the WHERE clause in your queries to ensure that you are not returning too many rows. Try to make the WHERE clause as specific as possible to ensure that the least number of rows are returned.
    § Queries that do not take advantage of indexes may also cause poor performance.

    6) Unnecessary round trips
    How it affects performance:
    Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
    Solution:
    Keep round trips to an absolute minimum.

    7) Too many open connections
    Connections are an expensive and scarce resource, which should be shared between callers by using connection pooling. Opening a connection for each caller limits scalability.
    Solution:
    To ensure the efficient use of connection pooling, avoid keeping connections open and avoid varying connection strings.

    8) Avoid Transaction misuse
    How it affects performance:
    If you select the wrong type of transaction management, you may add latency to each operation. Additionally, if you keep transactions active for long periods of time, the active transactions may cause resource pressure.
    Solution:
    Transactions are necessary to ensure the integrity of your data, but you need to ensure that you use the appropriate type of transaction for the shortest duration possible and only where necessary.

    9) Avoid Over Normalized tables
    Over Normalized tables may require excessive joins for simple operations. These additional steps may significantly affect the performance and scalability of your application, especially as the number of users and requests increases.

    10) Reduce Serialization
    Dataset serialization is more efficiently implemented in .NET Framework version 1.1 than in version 1.0. However, Dataset serialization often introduces performance bottlenecks.
    You can reduce the performance impact in a number of ways:
    Use column name aliasing§
    Avoid
    § serializing multiple versions of the same data
    Reduce the number of
    § DataTable objects that are serialized

    11) Do Not Use CommandBuilder at Run Time
    How it affects performance:
    CommandBuilder objects such as as SqlCommandBuilder and OleDbCommandBuilder are useful when you are designing and prototyping your application. However, you should not use them in production applications. The processing required to generate the commands affects performance.
    Solution:
    Manually create stored procedures for your commands, or use the Visual Studio® .NET design-time wizard and customize them later if necessary.

    12) Use Stored Procedures Whenever Possible
    Stored procedures are highly optimized tools that result in§ excellent performance when used effectively.
    Set up stored procedures to
    § handle inserts, updates, and deletes with the data adapter
    Stored
    § procedures do not have to be interpreted, compiled or even transmitted from the client, and cut down on both network traffic and server overhead.
    Be sure
    § to use CommandType.StoredProcedure instead of CommandType.Text

    13) Avoid Auto-Generated Commands
    When using a data adapter, avoid auto-generated commands. These require additional trips to the server to retrieve meta data, and give you a lower level of interaction control. While using auto-generated commands is convenient, it’s worth the effort to do it yourself in performance-critical applications.

    14) Use Sequential Access as Often as Possible
    With a data reader, use CommandBehavior.SequentialAccess. This is essential for dealing with blob data types since it allows data to be read off of the wire in small chunks. While you can only work with one piece of the data at a time, the latency for loading a large data type disappears. If you don’t need to work the whole object at once, using
    Sequential Access will give you much better performance.

    Tips for Asp.Net applications developed using VB

    1) Enable Option Strict and Option Explicit for your pages
    With Option Strict on, you protect yourself from inadvertent late binding and enforce a higher level of coding discipline.

    2) Use early binding in Visual Basic or JScript code
    Visual Basic 6 does a lot of work under the hood to support casting of objects, and many programmers aren’t even aware of it. In Visual Basic 7, this is an area that out of which you can squeeze a lot of performance.
    Solution:
    When you compile, use early binding. This tells the compiler to insert a Type Coercion is only done when explicitly mentioned.
    This has two major effects:
    Strange errors become easier to track down.§
    Unneeded
    § coercions are eliminated, leading to substantial performance improvements.
    When you use an object as if it were of a different type, Visual Basic will coerce the object for you if you don’t specify. This is handy, since the programmer has to worry about less code.

    3) Put Concatenations in One Expression
    If you have multiple concatenations on multiple lines, try to stick them all on one expression. The compiler can optimize by modifying the string in place, providing a speed and memory boost. If the statements are split into multiple lines, the Visual Basic compiler will not generate the Microsoft Intermediate Language (MSIL) to allow in-place concatenation.

    Summary
    When we talk about ASP.Net performance, there are lots of factors in place.
    Above discussed are the most critical of the speed improvements you can make in ASP.net that will have a dramatic impact on the user experience of your web application.

    if it is helpful, plese dont forget to leave a comment.