1、High performance Web Sites,richardchang,腾讯技术大讲堂,不知大家有没有看过这个ppt,以及这个架构图,Yahoos Case,Performance research and 14 rules,Exceptional Performance,started in 2004 quantify and improve the performance of all Yahoo! products worldwide center of expertise build tools, analyze data gather, research, and evang
2、elize best practices,Scope,performance breaks into two categories response time efficiency current focus is response time of web products,The Importance of Front-End Performance,percentage of time spent on the front-end,Back-end vs. Front-end,The Performance Golden Rule,80-90% of the end-user respon
3、se time is spent on the front-end. Start there.Greater potential for improvement Simpler Proven to work,Performance Research,http:/ Performance Rule,Vilfredo Pareto: 80% of consequences come from 20% of causesFocus on the 20% that affects 80% of the end-user response time.Start at the front-end.,Emp
4、ty vs. Full Cache,Empty vs. Full Cache,with an empty cache,Empty vs. Full Cache,Empty vs. Full Cache,Expires header,3,user re-requests ,with a full cache,Empty vs. Full Cache,empty cache2.4 secondsfull cache0.9 seconds 83% fewer bytes 90% fewer HTTP requests,How much does this benefit our users?,It
5、depends on how many users have components in cache.What percentage of users view a page with an empty cache*?* “Empty cache” means the browser has to request the components instead of pulling them from the browser disk cache.What percentage of page views are done with an empty cache*?,http:/ a new i
6、mage to your pagewith the following response headers:Expires: Thu, 15 Apr 2004 20:00:00 GMT Last-Modified: Wed, 28 Sep 2006 23:49:57 GMT,Browser Cache Experiment,Browser Cache Experiment,Requests from the browser will have one of these response status codes:200 The browser does not have the image in
7、 its cache. 304 The browser has the image in its cache, but needs to verify the last modified date.,Browser Cache Experiment,Surprising Results,40-60%,20%,Experiment Takeaways,Keep in mind the empty cache user experience. It might be more prevalent than you think!Use different techniques to optimize
8、 full versus empty cache experience.,http:/ Quick Review,HTTP response header sent by the web server: HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Set-Cookie: C=abcdefghijklmnopqrstuvwxyz; domain=,HTTP Quick Review,HTTP request header sent by the browser: GET / HTTP/1.1 Host: User-Agent:
9、Mozilla/4.0 (compatible; MSIE 6.0; Cookie: C=abcdefghijklmnopqrstuvwxyz;,HTTP Quick Review,HTTP request header sent by the browser: GET / HTTP/1.1 Host: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Cookie: C=abcdefghijklmnopqrstuvwxyz;,HTTP Quick Review,HTTP request header sent by the browser: GE
10、T / HTTP/1.1 Host: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Cookie: C=abcdefghijklmnopqrstuvwxyz;,HTTP Quick Review,HTTP request header sent by the browser: GET / HTTP/1.1 Host: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Cookie: C=abcdefghijklmnopqrstuvwxyz;,Impact of Cookies on Response
11、 Time, cookie sizes,Analysis of Cookie Sizes across the Web,Experiment Takeaways,eliminate unnecessary cookies keep cookie sizes low set cookies at appropriate domain level, or hosting assets on a new domain set Expires date appropriately earlier date or none removes cookie sooner,http:/ Downloads,T
12、wo components,in parallel,per hostname,HTTP/1.1,Parallel Downloads,Two in parallel Four in parallel Eight in parallel,Maximizing Parallel Downloads,response time (seconds),aliases,Maximizing Parallel Downloads,response time (seconds),aliases,Maximizing Parallel Downloads,response time (seconds),alia
13、ses,Maximizing Parallel Downloads,response time (seconds),rule of thumb: use at least two but no more than four aliases,Experiment Takeaways,consider the effects of CPU thrashing DNS lookup times vary across ISPs and geographic locations domain names may not be cached,14 Rules,How to optimize?,basic
14、 optimization rules optimizing assets (images, scripts, and styles) optimizations specific to scripts optimizations specific to styles,Basic Rules,Decrease Download Sizes Make Fewer HTTP Requests Combine scripts and style sheets Use image sprites Avoid redirects Avoid frames,14 things to check,Make
15、fewer HTTP requests Use a CDN Add an Expires header Gzip components Put CSS at the top Move JS to the bottom Avoid CSS expressions Make JS and CSS external Reduce DNS lookups Minify JS Avoid redirects Remove duplicate scripts Turn off ETags Make AJAX cacheable and small,Rule 1: Make fewer HTTP reque
16、sts,image maps CSS sprites inline images combined scripts, combined stylesheets,Image maps,server-side http:/./navbar.cgi?127,13 client-side preferreddrawbacks: must be contiguous defining area coordinates tedious, errors,http:/www.w3.org/TR/html401/struct/objects.html#h-13.6,CSS Sprites Preferred,s
17、ize of combined image is less,CSS Sprites Generator - http:/ http:/ background-image: url(sprite.png); background-position: -8px -40px; width: 16px; height: 16px; ,Combined Scripts, Combined Stylesheets,Combined Scripts, Combined Stylesheets,combining six scripts into one eliminates five HTTP reques
18、ts challenges: develop as separate modules number of possible combinations vs. loading more than needed maximize browser cache one solution: dynamically combine and cache,Rule 2: Use a CDN,distribute your static content before distributing your dynamic content,Rule 3: Add an Expires header,not just
19、for images,Setting Expires header in Apache,ExpiresActive On ExpiresByType application/x-javascript “modification plus 2 years“ ExpiresByType text/css “modification plus 5 years“,When modifing an asset?,Modify the asset name (automatically)! Append an epoch timestamp to the file name, e.g. img_11854
20、03733.png. Use the version number from your source control system (cvs or svn for example), e.g. img_1.1.png. Manually increment a number in the file name (e.g. when you see a file named img1.png, simply save the modified image as img2.png).,Rule 4: Gzip components,you can affect users download time
21、s 90%+ of browsers support compression,Gzip: not just for HTML,gzip scripts, stylesheets, XML, JSON (not images, PDF),Gzip Configuration,Apache 2.x: mod_deflate AddOutputFilterByType DEFLATE text/html text/css application/x-javascript HTTP request Accept-Encoding: gzip, deflate HTTP response Content
22、-Encoding: gzip Vary: Accept-Encoding,needed for proxies,Rule 5: Put CSS at the top,stylesheets block rendering in IE http:/ solution: put stylesheets in HEAD (per spec) avoids Flash of Unstyled Content use LINK (not import),Slowest is Fastest,Rule 6: Move scripts to the bottom,scripts block paralle
23、l downloads across all hostnames scripts block rendering of everything below them in the page IE and FF http:/ 6: Move scripts to the bottom,script defer attribute is not a solution blocks rendering and downloads in FF slight blocking in IE solution: move them as low in the page as possible,Rule 7:
24、Avoid CSS expressions,used to set CSS properties dynamically in IE width: expression( document.body.clientWidth 600 ? “600px” : “auto” ); problem: expressions execute many times mouse move, key press, resize, scroll, etc.http:/ 8: Make JS and CSS external,inline: HTML document is bigger external: mo
25、re HTTP requests, but cached variables page views per user (per session) empty vs. full cache stats component re-use external is typically better home pages may be an exception,Post-Onload Download,inline in front page download external files after onload window.onload = downloadComponents; function
26、 downloadComponents() var elem = document.createElement(“script“);elem.src = “http:/./file1.js“;document.body.appendChild(elem);. speeds up secondary pages,Example : Google,once the home page has finished loading, there is a request to get a sprite image, which is not actually needed until search re
27、sults page loads,Example : Yahoo,Conditional pre-loading - waits for the user to start typing in the search box. Once youve begun typing, its almost guaranteed that youll submit a search query.,Dynamic Inlining,start with post-onload download set cookie after components downloaded server-side: if co
28、okie, use external else, do inline with post-onload download cookie expiration date is key speeds up all pages,Rule 9: Reduce DNS lookups,typically 20-120 ms block parallel downloads OS and browser both have DNS caches,TTL (Time To Live),TTL how long record can be cached browser settings override TT
29、L,Browser DNS Cache,IE DnsCacheTimeout: 30 minutes KeepAliveTimeout: 1 minute ServerInfoTimeout: 2 minutes Firefox network.dnsCacheExpiration: 1 minute network.dnsCacheEntries: 20 network.http.keep-alive.timeout: 5 minutes Fasterfox: 1 hour, 512 entries, 30 seconds,Reducing DNS Lookups,fewer hostnam
30、es 2-4 (what about forums and blogs?) keep-alive,Rule 10: Minify JavaScript,minify inline scripts, too,Minify vs. Obfuscate,minify its safer,http:/ http:/dojotoolkit.org/docs/shrinksafe,Rule 11: Avoid redirects,3xx status codes mostly 301 and 302 HTTP/1.1 301 Moved Permanently Location: http:/ add E
31、xpires headers to cache redirects worst form of blocking,http:/www.w3.org/Protocols/rfc2616/rfc2616-sec10.html,Redirects,Avoid Redirects,missing trailing slash http:/ use Alias or DirectorySlash mod_rewrite CNAMEs log referer track internal links outbound links harder beacons beware of race conditio
32、n XHR bail at readyState 2,Rule 12: Remove duplicate scripts,hurts performance extra HTTP requests (IE only) extra executions atypical? 2 of 10 top sites contain duplicate scripts team size, # of scripts,Script Insertion Functions,“; ?,Rule 13: Turn off ETags,unique identifier returned in response E
33、Tag: “c8897e-aee-4165acf0“ Last-Modified: Thu, 07 Oct 2004 20:54:08 GMT used in conditional GET requests If-None-Match: “c8897e-aee-4165acf0“ If-Modified-Since: Thu, 07 Oct 2004 20:54:08 GMT if ETag doesnt match, cant send 304,The Problem with ETags,ETag for a single entity is always different acros
34、s servers ETag format Apache: inode-size-timestamp IIS: Filetimestamp:ChangeNumber Sites with 1 server return too few 304s (n-1)/n Remove them Apache: FileETag none IIS: http:/ 14: Make AJAX cacheable and small,XHR, JSON, iframe, dynamic scripts can still be cached, minified, and gzipped a personali
35、zed response should still be cacheable by that person,AJAX Example: Yahoo! Mail Beta,address book XML request GET /yab/. add last-modified-time in URL,Live Analysis,IBM Page Detailer,packet sniffer Windows only IE, FF, any .exe c:windowswd_WS2s.ini Executable=(NETSCAPE.EXE),(NETSCP6.EXE),(firefox.ex
36、e) free trial, $300 license,http:/ load time of pages alters config settings for faster loading Firefox extension free,http:/fasterfox.mozdev.org/,LiveHTTPHeaders,view HTTP headers Firefox extension free,http:/livehttpheaders.mozdev.org/,web development evolved inspect and edit HTML tweak and visual
37、ize CSS debug and profile JavaScript monitor network activity (caveat) Firefox extension free,http:/ lint tool grades web pages for each rule Firefox extension Yahoo! internal toolhttp:/ on the front-end harvest the low-hanging fruit you do control user response times LOFNO be an advocate for your users,