"A key aspect of Web application performance is site response time. See how you can boost it by preloading page data and displaying content only when appropriate"
Developing a Web application involves many design considerations and decisions. The most important is often response time—a performance consideration. One approach to improving site response time is to preload content and then display it only when the user needs to see it. You can do this by taking advantage of Dynamic HTML (DHTML) and JavaScript.
Each element within an HTML page is accessible via JavaScript. The DHTML style property contains the visibility property, which lets you control whether the element's contents are displayed on the page. To do this, you set the property to either visible or hidden. The following syntax may be used to access the property via JavaScript:
document.element_name.style.visibility = "visible";
or
document.element_name.style.visibility = "hidden";
The actual element is easily located by using its ID attribute and the getElementById JavaScript method:
document.getElementById("element name").style.visibility = "hidden";
Remember, HTML elements are assigned ID attributes to distinguish them within the page. This allows DHTML and JavaScript to locate and work with individual elements. The following HTML sample assigns individual names to HTML header elements and uses JavaScript to show and hide the second header:<html>
<head>
<title>div test</title>
</head>
<body>
<h1
id="header1"
onMouseOver='document.getElementById("header2").style.visibility="hidden";'
onMouseOut='document.getElementById("header2").style.visibility = "visible";'>
Now you see it!
</h1>
<h2 id="header2">
Now you don't!
</h2>
</body>
</html>
The code uses the onMouseOver and onMouseOut events of the first header element to show and hide the second header element. Notice that the name assigned to the second header via the ID attribute is used to control its visibility in the JavaScript.
This approach to displaying and hiding content is beneficial when only portions of a document are displayed at a time. It may be applicable for menus, expanding/collapsing page regions, and so forth. You can use this technique with any HTML element, but the DIV element stands out as a prime candidate when working with chunks of a page.
What is DIV?
The DIV element is used to give structure and context to block-level content within an HTML document. Everything between the start and ending DIV tags constitute the block, and the characteristics of the contained elements are controlled either by the DIV tag attributes or by applying style sheet formatting to the block. The DIV tag is supported by both Internet Explorer and Netscape browsers.
DIV vs. SPAN
Many developers confuse the DIV element with the SPAN element. Although they have the same characteristics, SPAN is used to define inline content as opposed to block-level content. You would use a DIV tag for a paragraph, but a SPAN tag would be useful for applying special characteristics to one or more words within the paragraph.
The DIV tag allows you to divide a Web page to handle formatting and presentation. You can combine it with the visibility technique to divide page content and show it as you choose. The following code sample uses the DIV tag to divide the page into sections; hyperlinks show and hide the sections:<html><head>
<title>div test</title>
<script language="JavaScript">
function setAllVisible() {
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";
}
</script></head>
<body onLoad='setAllVisible();'>
<h1>Builder.com Sample</h1>
<ul>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="visible";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";'>Section 1</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="visible";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";'>Section 2</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="visible";
document.getElementById("section4").style.visibility="hidden";'>Section 3</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="visible";'>Section 4</a></li>
</ul><br>
<div id="section1">Section 1 text.</div>
<div id="section2">Section 2 text.</div>
<div id="section3">Section 3 text.</div>
<div id="section4">Section 4 text.</body>
</html>
The code includes a JavaScript function to hide all DIV elements. The function is called when the document is loaded. Clicking each hyperlink shows the related section and hides the others. The drawback is that these methods are supported only in Internet Explorer 5 and above and Netscape Navigator 6 and above. However, I tested it with Mozilla 1.01 with no problems.
Display information only when necessary
Combining the power of DHTML and JavaScript enables you to preload page content and display portions when appropriate. This increases response time, thus improving performance for the user.
Tuesday, July 15, 2008
Increase site performance by selectively displaying preloaded content
Friday, July 11, 2008
Improving ASP.NET Application Performance and Scalability
any factors influence application performance, but in essence, the most important is to be aware of how to optimize your applications so they consume the least amount of memory and require the least amount of processing to produce the desired output in a managed environment.
This article discusses some best practices that you can follow during an application's development life cycle to help ensure that your application is both scalable and achieves high performance. You don't have to use special tools to achieve this, just write structured, readable code, paying particular attention to techniques that are instrumental for improving, optimizing and boosting the performance of .NET applications.
Reducing Page Load Time
Avoid excessively large images, redundant tags, and nested tables to facilitate faster page loads. Always avoid unnecessary roundtrips to the web server. Use client side scripts to dramatically reduce server roundtrips, thereby boosting the perceived, if not the actual application performance. Take advantage of the Page.IsPostback property to avoid unnecessary server processing on a roundtrip, reducing network traffic. I suggest you leave page buffering on (it is turned on by default) for a page unless you have a specific reason to turn it off.
You can pre-compile web pages in your application to reduce the working set size and boost application performance. Set AutoEventWireup attribute to false in the
<configuration>
<system.web>
<pages autoeventwireup="true|false">
</system.web>
</configuration>
The AutoEventWireup attribute accepts a Boolean value that indicates whether the ASP.NET pages events are auto-wired. If the AutoEventWireup is set to false, the runtime does not have to look for each of the page event handlers. This MSDN article about the AutoEventWireup Event concludes with, "When you explicitly set AutoEventWireup to true, Visual Studio .NET or Visual Studio 2005, by default, generates code to bind events to their event-handler methods. At the same time, the ASP.NET page framework automatically calls the event-handler methods based on their predefined names. This can lead to the same event-handler method being called two times when the page runs." The article therefore recommends that you always set AutoEventWireup to false while working in Visual Studio .NET.
Efficient ASP.NET State Management Practices
ViewState is great for storing control state but can degrade performance—especially on web sites with large page sizes. If you've ever looked at a page that contains a large DataSet, you know the amount of data stored in ViewState can be overwhelming. Every byte added to a web page by enabling its ViewState causes two bytes of network traffic, one in each direction. Evaluate whether each web page you write requires ViewState and avoid it when possible to speed up the page-load cycle in your applications. You should typically use ViewState only for controls that need to persist state. You can turn ViewState on or off at four levels: machine, application, page, and control. Limiting the size of the ViewState and eliminating its unnecessary usage would boost the application performance to a large extent due to the reduced size of the rendered pages and hence the network traffic. It should be noted that each byte of the view state causes two bytes of network traffic for each request, one from the server to the client and the other from the client to the server. For more information on ViewState and how to turn it off at control, page, application, or machine levels, see this article .
You can remove the runat="server" form tag completely to reduce page size by 20 bytes. If you don't remove this tag, the page itself passes on about 20 bytes of information to ViewState—even when the page's ViewState property is set to false.
Caching is one of the best strategies for storing relatively static application data. Caching reads data from memory to avoid repeatedly retrieving data from a database, file, or any other repository, and it can provide huge application performance gains. Use Page Output, Page Fragment or Data Caching directives depending on your requirements. Cache application-wide data that multiple users of the application need to share and access, but avoid storing user-specific data in the cache.
Use Session State only for storing a single user's session data. Avoid storing too many objects in the Session and turn Session State off for pages that do not need to access session data. You can turn Session State on or off at the same four levels as ViewState: machine, application, page, and control.
Note that there are three Session State storage modes. The right type of storage mode to choose depends on factors such as, speed, security, scalability, and reliability. Even though the InProc mode of Session State storage is the fastest, it is not at all well suited to a production environment and not scalable for large sites. The OutProc storage mode is well-suited for web sites with heavy traffic, while the SqlServer mode is great for securing session data. No matter which mode you choose though, Session State has one major disadvantage: the resource will be increasingly strained as you scale up. There are always tradeoffs. The best mode for security, scalability, and reliability is not always the best mode for performance, and vice versa.
Tips for Efficient Memory and Resource Management
I've listed a few tips in this section that can help you avoid problems. I don't have room to explain each tip in-depth here; instead, I've provided a basic description and added links where appropriate so you can explore further on your own.
Try never to refer to a short-lived object from a long lived one to avoid promoting short-lived objects to higher generations. Note that the .NET Garbage Collector (GC) works more frequently against lower generations than against higher ones. An in-depth discussion of the .NET GC is beyond the scope of this article, but this two-part MSDN article on garbage collection (Part 1, Part 2) provides more background
Avoid any code that can promote an object to a higher generation unnecessarily as shown in the code snippet below:
class Employee
{
EmployeeRegister empRegister;
void Create (int empCode, int deptCode, double basic)
{
EmployeeRegister empRegister = new EmployeeRegister();
empRegister.Create(empCode, deptCode, basic);
this.empRegister = empRegister;
}
}
Use Dispose and Finalize appropriately to handle unmanaged resources (for more information, see my article When and How to Use Dispose and Finalize in C#. In fact, you should avoid implementing the Finalize method as much as possible.Set any objects no longer required to null prior to making any long-running calls. Developers often set locals to null after they're done using them, but in .NET, that's not required, as the GC can safely determine when objects are no longer needed or are not reachable, thus making them eligible for garbage collection. However, if you use machine resources such as files, database connections, or unmanaged objects, remember to release them in a finally block—never in a catch block.
Author's Note: In C#, it's best to wrap resource-handling code within a using block to ensure that the resources are disposed of properly when they're no longer needed. When you use the statement, the .NET framework implicitly creates usingfinally blocks for those objects that implement IDisposable.
Acquire resources and locks late and dispose of them as soon as possible. Ensure that you free or dispose unneeded resources and locks properly. In fact, I recommend that you avoid locking and synchronization altogether unless it's absolutely necessary. Do not lock on the this object—it's better to lock on a private object. If you lock on the current object instance (this), all the members of the object are also locked irrespective of whether a lock is required on them. Do not lock on object types, only on objects themselves
Efficient Exception Management
Exceptions are errors that occur at run time. Exceptions are generally well understood but quite often used improperly. An understanding of proper exception handling is one of the more important aspects of efficient programming.
Handle only those exceptions that you know how to handle and avoid handling those that you don't know how to handle. As Eric Gunnerson, a former member of Microsoft's C# team, says in his blog, "the essence of exception handling is to be able to respond to a specific exception in a specific situation."
When possible, reduce the number of try...catch blocks in your code; exceptions take longer to be processed and can reduce application performance drastically. Do not use exceptions to control an application's logic flow. Use proper validation techniques instead of exceptions to avoid throwing unnecessary exceptions.
Efficient Data Access Strategies
Prefer DataReaders to DataSets. DataReaders are much faster than DataSets for simple sequential data access. Use a DataReader for fast data-rendering, but not to pass data between layers of the applications or through different application domains—unlike DataSets which can work in disconnected mode and can be cached, DataReaders always require an open connection. When you do have to use a DataSet, you can often set its EnableConstraints property to false and use the BeginLoadData and EndLoadData methods for faster data rendering. If you are using transactions keep them short to minimize the lock durations and to improve data concurrency.
Open database connections as late as possible and close them immediately when done. Effective use of connection pooling can increase application performance by reducing the number of roundtrips to the server. Note that each database request in a distributed environment creates network traffic that can cause performance bottlenecks and degrade the application's performance. Try to minimize the number of database connections in the application. Never hold a connection open, because that decreases the number of available connections in the connection pool and hence degrades performance if the demand for connections exceeds the pool count. See this article for more information on connection pooling.
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.
You should seal final classes (those that cannot be inherited) for performance gains.
Avoid recursive method calls and try to replace them with loops instead. Inline frequently called code inside loops. Avoid calling methods or properties repetitively inside a loop. Especially, avoid situations that will require boxing and unboxing of value types, because that carries performance overhead—use generics instead when possible, building strongly typed collections to avoid boxing and unboxing issues. This link provides more information.
Avoid inefficient string operations (see this article for more information) and use collections (if needed) efficiently.
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.
Use Best Practices—and Common Sense
Even though there is no specific methodology that can fit in each and every environment, using best practices such as those discussed in this article can yield better application performance. You should plan and set some well-defined performance objectives, create performance test plans, performance checklists, and perform periodic tests based on the test plans. Keep these performance factors in mind when designing applications. This process should be iterative and repeated until we meet the predefined performance goals.
Application Performance Issues Cause Organizations to Lose Millions, According to New Aberdeen Group Study
LEXINGTON, Mass., July 8 /PRNewswire/ -- Application performance issues
are impacting overall corporate revenues by up to 9 percent, according to a
new benchmark report by Aberdeen Group, a Harte-Hanks company (NYSE: HHS)
sponsored in part by Gomez, Inc., a leading provider of web application
experience management services.
Entitled "The Lifecycle Approach Brings IT and Business Together," the
report surveyed 206 organizations between May and June 2008 and found that
58 percent of the organizations surveyed are unsatisfied with the
performance of applications that they currently use. Their top challenge is
the inability to identify issues before end users are impacted.
"Being proactive about managing application performance is no longer
optional," said Bojan Simic, research analyst, Aberdeen. "What can no
longer be ignored is the impact that application performance is having on
some of the key metrics such as revenue growth, customer satisfaction,
employee productivity, and profitability."
Using key performance criteria to distinguish Best-in-Class companies
from Industry Average companies and Laggards, the report found that
Best-in-Class companies were five times more likely to report improvements
in quality of end user experience. It found that 65 percent of
Best-in-Class companies have the ability to measure the quality of end user
experience, with 81 percent reporting improved customer satisfaction.
Additionally, what allowed Best-in-Class organizations to outperform
the overwhelming majority of their peers was a full lifecycle approach to
application performance management including the deployment of capabilities
for predicting, monitoring, analyzing, and optimizing application
performance. For example, 63 percent of Best-in-Class companies use tools
for monitoring web application performance and 48 percent use tools to load
test their web applications.
The report also found that Best-in-Class organizations experienced:
-- 85 percent improved success rates in preventing issues with
application performance before end users are impacted, as opposed to
Laggards who reported zero percent improvement; and
-- 106 percent average improvement in application availability,
compared to Laggards who reported two percent improvement.
"Aberdeen's findings empirically underscore the correlation between
quality web experiences and business success," said Matt Poepsel, Gomez VP
of performance strategies. "For too many businesses, the end user's
experience remains clouded in obscure information -- or no information at
all -- putting business, brand and profits at risk. The Gomez(R)
ExperienceFirst(SM) platform of services helps businesses ensure quality
end user experiences by testing their web applications in development and
measuring them after deployment, mirroring the proactive, lifecycle
approach to managing and improving application performance prescribed by
Aberdeen in this report."