performance optimization

15
5/30/2011 Performance Optimization of Web Application | [email protected] DIASPA RK HOW TO IMPROVE WEB APPLICATION PERFORMANCE

Upload: neha-thakur

Post on 22-Jan-2015

156 views

Category:

Design


5 download

DESCRIPTION

 

TRANSCRIPT

  • 1. 5/30/2011 Performance Optimization of Web Application | [email protected] DIASPARK HOW TO IMPROVE WEB APPLICATION PERFORMANCE

2. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE Table of Contents What are the major Performance Problem Areas in a Web System?....................................................5 Typical performance problems contributors .......................................................................................6 1. Minimize HTTP based Requests:..............................................................................................7 2. HTTP Compression......................................................................................................................8 3. Correct Formatted Images at the Right Place...............................................................................8 4. Compress CSS, JavaScript and Images..........................................................................................9 5. CSS at Top ..................................................................................................................................9 6. JavaScript at Bottom...................................................................................................................9 7. Content Delivery Network: (CDN)................................................................................................9 8. Ajax..........................................................................................................................................10 9. Ajax vs. Callback.......................................................................................................................10 10. Reduce Cookie size .................................................................................................................10 11. Use Cache appropriately .........................................................................................................11 12. Upload compiled code rather than source code.......................................................................11 Conclusion:......................................................................................................................................11 References:......................................................................................................................................12 3. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE In the event of a competitive market and to release/launch the products/software first in the market often most of the clients make disastrous mistakes. One of them is developing their apps or products rapidly but in the events following the performance of the app/software degrades and left an immense aftermath. After studying few websites and from experience I have created this document on How to Improve Web Applications Performance. Performance tuning is the improvement of system performance. Most systems will respond to increased load with some degree of decreasing performance. A system's ability to accept higher load is called scalability, and modifying a system to handle a higher load is synonymous to performance tuning. The major Performance engineering Objectives are: Increase business revenue by ensuring the system can process transactions within the requisite timeframe Eliminate system failure requiring scrapping and writing off the system development effort due to performance objective failure Eliminate late system deployment due to performance issues Eliminate avoidable system rework due to performance issues Eliminate avoidable system tuning efforts Avoid additional and unnecessary hardware acquisition costs Reduce increased software maintenance costs due to performance problems in production Reduce increased software maintenance costs due to software impacted by ad hoc performance fixes Reduce additional operational overhead for handling system issues due to performance problems According to Wikipedia, Systematic tuning follows these steps: 1. Assess the problem and establish numeric values that categorize acceptable behavior. 2. Measure the performance of the system before modification. 3. Identify the part of the system that is critical for improving the performance. This is called the bottleneck. 4. Modify that part of the system to remove the bottleneck. 5. Measure the performance of the system after modification. This is an instance of the measure-evaluate-improve-learn cycle from quality assurance. 4. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE A performance problem may be identified by slow or unresponsive systems. This usually occurs because high system loading, causing some part of the system to reach a limit in its ability to respond. This limit within the system is referred to as a bottleneck. A handful of Techniques used to improve performance. Among them is: 1. Code optimization: Enhancing performance by rewriting specific portions of a program to run faster is one form of code optimization. The term code optimization can refer to improving the implementation of a particular algorithm for performing a task (code tuning). Examples of code optimization include improving the code so that work is done once before a loop rather than inside a loop or replacing a call to a simple selection sort with a call to the more complicated algorithm for a quicksort. 2. Load balancing: Load balancing is often used to achieve further gains from a distributed system by intelligently selecting which machine to run an operation based on how busy all potential candidates are, and how well suited each machine is to the type of operation that needs to be performed. 3. Caching strategy: Caching is a fundamental method of removing performance bottlenecks that are the result of slow access to data. Caching improves performance by retaining frequently used information in high speed memory, which reduces access time and thus improves performance. 4. Distributed computing: Distributed computing is used to increase the performance of operations that can be performed in parallel, by concurrently executing multiple operations. Operations may be distributed across multiple processes on a single CPU, taking advantage of multitasking, multiple processes across multiple CPUs, or across multiple machines. As operations are executed concurrently, ensuring synchronization between processes is essential to ensure correct results. 5. Self-tuning: A self-tuning system is capable of optimizing its own internal running parameters in order to maximize or minimize the fulfillment of an objective function; typically the maximization of efficiency or error minimization. 6. Bottlenecks: The bottleneck is the part of a system which is at capacity. Other parts of the system will be idle waiting for it to perform its task. In the process of finding and removing bottlenecks, it is important to prove their existence, such as by sampling, before acting to remove them. There is a strong temptation to guess. 5. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE What are the major Performance Problem Areas in a Web System? End-User desktop problems Internet bottleneck s ISP performance and peering Network vs. Server Issues Faulty webserver within a cluster Firewall performance Server HW, device, OS, DB issues Content Issues Load balancer Problems Application Server Issues ISP2 Hub Router ISP1 Router Firewall Firewall Load Balancer Web Server Application Server DB Server External datafeed 6. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE Typical performance problems contributors Application Server Issues Threading Issues Memory Leaks High Verbose Log File Connection Pool Management DB Server Issues Slow Query response Query and Stored Procedure cache related issues Deadlocks Temp DB Issues Network Issues Packet Loss Excessive Network usage by Chatty apps Hardware related issues(Routers, etc) High Latency Web Server Issues Ineffective caching Connection Pool Management Keep-Alive Connections Flushed Content Compression Configuration High Amount of Disk I/O on Servers Low CPU usage across servers but overall Poor Performance High Processor Queue Length High CPU Usage on Servers Applicatio n Server , 40 % Network, 2 0 % Web Server, 10 % DB Server, 30 % 7. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE Now after discussing various issues hindering performance of Web Apps we will focus on Optimizing the performance related issues. The following are a few points that can make a site scalable and reliable; but which may initially slow down development. This list is a consolidated list form various sites mentioned in reference section below: 1. Minimize HTTP based Requests: 80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages. One way to reduce the number of components in the page is to simplify the page's design. But is there a way to build pages with richer content while also achieving fast response times? Here are some techniques for reducing the number of HTTP requests, while still supporting rich page designs. Problem 1: Serving images - no matter if they are of less than 1 KB - as separate web resources, because separate web requests to the server, which impact performance. Solutions: Use Image Maps to merge up images, though image Maps could only merge up those images which are in sequence, like navigation images, so it depends upon your web site/page design. The overall size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be tedious and error prone. Using image maps for navigation is not accessible too, so it's not recommended. Use Inline images. Inline images could increase your HTML page size but would cause fewer requests to the server. Use the data: URL scheme to embed the image data in the actual page. Combining inline images into your (cached) stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages. Inline images are not yet supported across all major browsers. CSS Sprites can also be used to merge up images and setting their position and backgrounds. (CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.) Problem 2: Using CSS is very good practice but serving stylesheets as separate resources, thus causing separate requests, should be considered very carefully. Solutions: Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times. 8. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE .css files are normally cached by browsers, so a single and heavy .css file doesnt cause a long wait on each page request. Inline .css classes could make HTML heavy, so again: go ahead with a single.css file. If you use a lot of CSS and JavaScript in your HTML document, you wont be taking advantage of the web browsers caching features. Problem 3: JavaScript is an awesome scripting language which can be quite powerful to play with. Nonetheless, it should be used carefully not only for request size issues; but also because it can have a way of causing unpredictable performance issues. Solution: Inline JavaScript could make the HTML page heavy, so its preferred to serve separate .js files or a single JavaScript file to keep all JavaScript-based scripts in a single place. JavaScript files also get cached automatically by browsers, so they usually arent requested each time the page is loaded by the browsers. 2. HTTP Compression HTTP Compression is used to compress contents from the web server. HTTP requests and responses could be compressed, which can result in great performance gains. Through HTTP compression, the size of the payload can be reduced by about 50%, which is great. Isnt it? HTTP Compression is now widely supported by browsers and web servers. If HTTP compression is enabled on the web server, and if the request header includes an Accept- Encoding: GZip, deflate header, the browser supports GZip and deflate compression mechanisms, so the response can be compressed in any of the given formats by the web server in order to reduce the payload size. This leads to an increase in performance. Latter that compressed response is decompressed by the browser and rendered normally. Following are very good links which detail HTTP Compression and their implementations: Click here to get detailed knowledge on HTTP compression. Click here to learn how to enable HTTP compression in IIS. 3. Correct Formatted Images at the Right Place Problem: Normally designers use JPG or GIF formats quite randomly and ignore some other good formats to compress images. Solution: Correct format should be used for right purpose like If you have to place a background image, some large image or a screenshot then the suggested format is JPG/JPEG. If you have to use small graphics like button images, header images, footer images, navigation bar images or clip arts, then the suggested format is PNG. If an image is not required to be in high or true colors and 256 colors are enough, then GIF is preferred. 9. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE 4. Compress CSS, JavaScript and Images CSS files (.css), images and JavaScript (.js) files can be compressed, as normally .css and .js files contain unnecessary spaces, comments, unnecessary code and such other things. A number of high quality (and free) utilities are available to help you pre-compress your files. Following are a few good links for such utilities: Compress PNG images by clicking here Compress JPG images by clicking here Compress .CSS files by clicking here and here and here Compress .Js files by clicking here and here and here I have used these utilities and seen compression results of about 50% in file size reduction after using such loss-less compression, so I recommend them. 5. CSS at Top The recommended approach is to put CSS links on top of the web page, as it makes the page render progressively efficient. Since users want to see the contents of a page whilst its loading rather than white spaces, contents/formats should be given on top. HTML Specifications clearly say to declare style sheets in the head section of a web page. 6. JavaScript at Bottom When scripts are defined on top of the page they can take unnecessary time to load; they dont show the contents that users are expecting after making any request to an HTTP web server. It's better to display the HTML contents of a page, and then load any scripting code (when possible, of course). Preferably use/link up JavaScript-based scripts at the bottom of a web page. Alternatively you can use the defer attribute, which runs the script at the end of page loading, but that is not the preferable approach as it is not browser independent. For example, Firefox doesnt support it and could mess up with document.write, so only use it once you fully understand the implications. 7. Content Delivery Network: (CDN) When a browser makes a request to any web page that is, he types a URL/URI of any web page or web site, a request goes through many hops (routers and computers) and then finally reaches its final destination. This happens both for requests and responses. This operation affects performance and can severely effect load time. A Content Delivery Network implies a collection of computers, distributed all over the world, which deliver data (contents). Through a CDN you can have your website data on multiple servers distributed in different locations around the world. Distribute web application data in different places around the world so request can be served from the nearest location and save time (which means performance and money as well). 10. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE 8. Ajax Problem: Ajax is being increasingly used to improve usability, but oftentimes in a way which increases overall server load. Solutions: Preferably use the GET method for Ajax based Requests, because if you use POST method then the request header would be sent first, followed by the data, which basically splits the request in two steps. A single-step request can be achieved with GET if a cookie is not too long and the URL is not larger than 2k. When using ASP.NET AJAX and the UpdatePanel control for partial page rendering, use the maximum number of update panels to update small chunks of page, but use them wisely. Dont set the Update property to Always unless needed. Instead, set the update mode to Conditional, otherwise all the partial chunks would be sent together after each asynchronous postback. Ajax based requests can also be cached when using the GET method. If the URL is the same, then cached data can be used from the client, and a round trip to the server can be avoided. 9. Ajax vs. Callback Problem: Ajax is a great solution for asynchronous communication between client (web browser) and HTTP servers, but one solution can't be applied to every problem. This means that Ajax is great mechanism for sending requests to the server without making a full page postback, but what if you need to send a request to the server and dont even need partial rendering? Solution: best solution is Callback. For example, if you need to check whether a user exists or not, or if a user has forgotten his/her password and you just need to send a request to the server to check if user name exist, there is no need for client-side render - just a server side operation. Following are a couple of great links which explain callbacks: Please click here and here. 10. Reduce Cookie size Cookies are stored on the client side to keep information about users (authentication and personalization). Since HTTP is a stateless protocol, cookies are common in web development to maintain information and state. Cookies are sent with every HTTP requests, so try to keep them low in size to minimize effects on the HTTP response. Cookies size should be minimized as much as possible. Cookies shouldnt contain secret information. If really needed, that information should be either encrypted or encoded. Try to minimize the number of cookies by removing unnecessary cookies. Cookies should expire as soon as they become useless for an application. 11. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE 11. Use Cache appropriately Cache mechanism is a great way to save server round trips - and also database server round trips - as both round trips are expensive processes. By caching data we can avoid hitting them when unnecessary. Following are few guidelines for implementing caching:: Static contents should be cached, like Contact us and About us pages, and such other pages which contain static information. If a page is not fully static, it contains some dynamic information. Such pages can leverage the ASP.NET technology, which supports partial page caching. If data is dynamically accessed and used in web pages - like data being accessed from some file or database - and even if data is consistently or regularly changed, then that data could be cached by using ASP.NET 2.0 cache dependency features. As soon as data changes from the back-end by some other means, the cache would be updated. Now that web technologies such ASP.NET has matured and offers such great caching capabilities, there's really no reason not to make extensive use of them. Following are few very good links to implement caching for different types of data (static and dynamic): Click here to cache Full page (static page caching). Click here and here to cache partial page caching. Click here to cache dynamic data with dependency. 12. Upload compiled code rather than source code Pre-compiled ASP.NET pages perform much better than source code versions. Actually pre-compilation give web sites a performance boost especially when the first request is made to a folder containing that resource. Uploading a pre-compiled version boosts up performance since the server doesnt need to compile a page at request-time. Conclusion: Following are few good practices to gain better performance: For HTTP compression, GZip is considered the most effective and most popular by means of browsers and HTTP server. It can reduce file size up to 70% in size. Always keep JavaScript and CSS in external files. Avoid redirects until needed. Server. Transfer is also provided so consider that as well since it performs better in some conditions. Minimize use of Iframes as its costly. Avoid try-catch blocks for control-flow as they perform poorly. Exceptions should be used only in truly exceptional situations. Minimize Cookie/CSS sizes. Minimize DOM objects on page as they are heavy weight. 12. May 30, 2011 HOW TO IMPROVE WEB APPLICATION PERFORMANCE Use link tags rather than @import to use/link up CSS. Favicon, being a static image displayed in the browsers address bar, should be cacheable and compressed. Always prefer a cache-friendly folder structure. For example, create specific folders for static contents, like /static for static images/static pages SSL can never be cached so minimize its usage. Keep it for those pages which need to be secure, rather than using it for all the pages. HTTP Post requests cant be cached, so choose the HTTP method appropriately. Prevent Denial of Service (Dos) attacks. Recommended article here. Prevent SQL Injection. Recommended article here. Prevent Cross Site Scripting (XSS). Recommended article here. I hope you have learned some very good approaches and techniques to keep your web application in good shape on an HTTP server. I personally dont think any are flat-out ignorable nor is any too difficult to implement. As performance is a vital part of success for any web application, I have tried to be as general as possible, so every web technology (ASP.NET, asp, php, jsp, jsf and so on) can follow these tips. References: http://dotnetslackers.com/articles/aspnet/ImproveWebApplicationPerformance.aspx http://developer.yahoo.com/performance/rules.html http://sixrevisions.com/web-development/10-ways-to-improve-your-web-page-performance/ http://www.codeproject.com/KB/aspnet/Application_Performance.aspx http://www.webperformance.com/library/reports/AjaxBandwidth/ http://en.wikipedia.org/wiki/Performance_engineering http://en.wikipedia.org/wiki/Performance_tuning http://isqtinternational.com/capgemini.pdf