SlideShare a Scribd company logo
JavaScript: The Good Parts Part Six: Ajax Performance Douglas Crockford [email_address]
Memento
The Sessionless Web Cookies for pseudosessions. Cookies enable CSRF attacks. Every action results in a page replacement. Pages are heavy, complicated, multipart things. The web is a big step backwards in individual productivity.
“ When your only tool is a hammer, every problem looks like a webpage.”
The Ajax Revolution The page is an application with a data connection to a server.
When the user does something, we send a JSON message to the server, and receive a JSON message as the result.
A JSON message is less work for the server to generate, moves faster on the wire, and is less work for the browser to parse and render  than an HTML document.
 
 
 
 
 
 
 
 
 
 
Division of Labor How is the application divided between the browser and the server?
Pendulum of Despair Server  The browser is a terminal.
Pendulum of Despair Server  Browser The browser is a terminal The server is a file system.
Seek the Middle Way. A pleasant dialogue between specialized peers.
Ajaxify The client and server are in a dialog. Make the messages between them as small as possible. The client does not need a copy of the database. It just needs, at any moment, just enough information to serve the user. Don't rewrite the server application in JavaScript!
The Poor Browser The browser is a very inefficient application platform. If your application becomes bloated, performance will be very bad. Try to keep the client programming light.
Amazingly, the browser works But it doesn't work well. It is a difficult platform to work with. There are significant security problems. There are significant performance problems. It was not designed to be an application delivery system. Ajax pushes the browser really hard.
Correctness First Do not worry about optimization until you have the application working correctly.  If it isn’t right, it doesn’t matter if it is fast. Test for performance early.  Test in customer configurations: Slow networks, slow computers. Internal networks and developer-class machines can mask performance problems.
Premature optimization is the root of all evil. — Donald Knuth Use YSlow to reduce startup time. Don't optimize until you need to, but find out as early as possible if you need to. Clean, correct code is easier to optimize. Tweaking is usually  ineffective. Sometimes restructuring or redesign is required.
Example var fibonacci = function (n) { return n < 2 ? n :  fibonacci(n - 1) +  fibonacci(n - 2); };   fibonacci(40) Calls itself 331,160,280 times.
Memoizer var memoizer = function (memo, fundamental) { var shell = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; };
Memoizer var fibonacci =  memoizer([0, 1], function (recur, n) { return recur(n - 1) + recur(n - 2); }); fibonacci(40) Calls itself 38 times. The key to optimization is work avoidance.
Code Quality High quality code is most likely to avoid platform problems. Code Conventions for the JavaScript Programming Language http://javascript.crockford.com/code.html Use JSLint.com. Pass with no warnings.
Have regular code readings. Don’t wait until release to do code reviews. Do team code reading regularly during development. Experienced developers can lead by example. Novice developers learn from the group. Problems can be discovered early. Good techniques can be shared early.
Two Kinds of Optimization Streamlining Algorithm replacement Work avoidance Code removal These things are always good to do Special Casing Adds cruft, increases code size Should only be done when proven necessary
Avoid unnecessary displays or animation. Everything costs. Wow costs.  As the number of widgets on the page increases, overall ongoing performance gets worse.
Only speed up things that take a lot of time. Speeding up things that take very little time will yield very little improvement.
Only speed up things that take a lot of time. If profiling shows that you are spending most of your time in A, don't bother optimizing C. A B C D
Improving performance If JavaScript were infinitely fast, most pages would run at about the same speed. The bottleneck tends to be the DOM interface. There is a significant cost every time you touch the DOM tree.  Each touch can result in a reflow computation, which is expensive.
Touch lightly It is faster to manipulate new nodes before they are attached to the tree. Touching unattached nodes avoids the reflow cost. Setting  innerHTML  does an enormous amount of work, but browsers are really good at it, and it only touches the DOM once.
Make good use of Ajax Libraries Effective code reuse will make widgets more effective.
How IE8 Spends Its Time Average time allocation of the Alexa 100: Layout  43.16% Rendering  27.25% HTML 2.81% Marshalling  7.34% DOM  5.05% Format  8.66% JScript  3.23% Other 2.5%
How IE8 Spends Its Time Opening a thread in GMail: Layout  9.41% Rendering  9.21% HTML 1.57% Marshalling  7.85% DOM  12.47% Format  38.97% JScript  14.43% Other 3.72%
Coding Efficiency Common subexpression removal. Loop invariant removal. Most compilers in most programming languages do these optimizations for you. But not JavaScript.
Before var i; for (i = 0; i <  divs.length ; i += 1) { divs[i].style. color = &quot;black&quot;;  divs[i].style. border =  thickness +  'px solid blue' ;  divs[i].style. backgroundColor = &quot;white&quot;;  }
After var  border  =  thickness + 'px solid blue' , nrDivs  =  divs.length , ds , i; for (i = 0; i <  nrDivs ; i += 1) { ds  =  divs[i].style ; ds .color = &quot;black&quot;;  ds .border =  border ;  ds .backgroundColor = &quot;white&quot;;  }
Strings Concatenation with  + Each operation allocates memory foo = a + b; Concatenate with array .join('') The contents of an array are concatenated into a single string foo = [a, b].join('');
Don't Tune For Quirks Some browsers have surprising inefficiencies. A trick that is faster on Browser A might be slower on Browser B. The performance characteristics of the next generation may be significantly different. Avoid short-term optimizations.
Don't Optimize Without Measuring Intuitions are often wrong. start_time = new Date().valueOf(); code_to_measured(); end_time = new Date().valueOf(); elapsed_time = end_time - start_time; A single trial is unreliable. Timers can be off by as much as 15 msec. Even accurate measurements can lead to wrong conclusions.
O  (1) An operation that is performed only once is not worth optimizing.
O  ( n ) An operation that is performed many times may be worth optimizing. Time n Slope: Time per Iteration Fixed time: Startup and cleanup
The Axis of Error Inefficiency Time n Inefficiency
The Axis of Error Frustration Time n Frustration
The Axis of Error Failure Time n Failure
O  ( n ) Time n Slope: Time per Iteration
O  ( n  log  n ) Time n
O  ( n 2 ) Generally not suitable for browser applications except when  n  is very small. Time n
The most effective way to make programs faster is to make  n  smaller. Ajax allows for just-in-time  data delivery.
The Wall.

More Related Content

PPT
The Theory Of The Dom
PDF
Secrets of JavaScript Libraries
PPT
GWT is Smarter Than You
PDF
The DOM is a Mess @ Yahoo
PDF
JavaScript Library Overview
KEY
Mobile optimization
PDF
Performance Optimization and JavaScript Best Practices
PDF
Maintainable JavaScript 2011
The Theory Of The Dom
Secrets of JavaScript Libraries
GWT is Smarter Than You
The DOM is a Mess @ Yahoo
JavaScript Library Overview
Mobile optimization
Performance Optimization and JavaScript Best Practices
Maintainable JavaScript 2011

What's hot (20)

PDF
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
PPT
jQuery with javascript training by Technnovation Labs
KEY
Mobile HTML, CSS, and JavaScript
PDF
Even more java script best practices
PDF
jQuery Proven Performance Tips & Tricks
PPT
JavaScript Misunderstood
PDF
Unit and functional testing with Siesta
PPT
GWT Introduction and Overview - SV Code Camp 09
PDF
Building scalable applications with angular js
PDF
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
PDF
Javascript Module Patterns
PDF
Building a Startup Stack with AngularJS
PDF
React
ODP
Object Oriented Javascript
PPT
JavaScript 2.0 in Dreamweaver CS4
PDF
Create responsive websites with Django, REST and AngularJS
PPT
JavaOne TS-5098 Groovy SwingBuilder
PDF
High Performance JavaScript - WebDirections USA 2010
PDF
Thomas Fuchs Presentation
PDF
AngularJS - Overcoming performance issues. Limits.
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
jQuery with javascript training by Technnovation Labs
Mobile HTML, CSS, and JavaScript
Even more java script best practices
jQuery Proven Performance Tips & Tricks
JavaScript Misunderstood
Unit and functional testing with Siesta
GWT Introduction and Overview - SV Code Camp 09
Building scalable applications with angular js
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Javascript Module Patterns
Building a Startup Stack with AngularJS
React
Object Oriented Javascript
JavaScript 2.0 in Dreamweaver CS4
Create responsive websites with Django, REST and AngularJS
JavaOne TS-5098 Groovy SwingBuilder
High Performance JavaScript - WebDirections USA 2010
Thomas Fuchs Presentation
AngularJS - Overcoming performance issues. Limits.
Ad

Viewers also liked (14)

KEY
Douglas Crockford - Programming Style and Your Brain
PDF
Performance, Games, and Distributed Testing in JavaScript
PPT
The JSON Saga
PDF
Performance Improvements in Browsers
PPT
Douglas Crockford - Ajax Security
PDF
Building a JavaScript Library
PPT
PPT
OOP in JavaScript
PDF
Good Parts of JavaScript Douglas Crockford
PPT
Advanced Javascript
PPTX
Advanced JavaScript Concepts
PDF
Scalable JavaScript Application Architecture
PDF
The JavaScript Programming Language
PDF
Speed Up Your JavaScript
Douglas Crockford - Programming Style and Your Brain
Performance, Games, and Distributed Testing in JavaScript
The JSON Saga
Performance Improvements in Browsers
Douglas Crockford - Ajax Security
Building a JavaScript Library
OOP in JavaScript
Good Parts of JavaScript Douglas Crockford
Advanced Javascript
Advanced JavaScript Concepts
Scalable JavaScript Application Architecture
The JavaScript Programming Language
Speed Up Your JavaScript
Ad

Similar to Ajax Performance (20)

PDF
Maintainable Javascript carsonified
PPSX
Magento performancenbs
PPTX
Web performance
DOCX
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
PPTX
Natural Laws of Software Performance
PPT
Developing For The Web
PPT
High Performance Ajax Applications 1197671494632682 2
PPT
High Performance Ajax Applications
PPTX
Performace optimization (increase website speed)
PPT
Web Speed And Scalability
PPT
Why test with flex unit
PPT
Windy cityrails performance_tuning
PPT
Ruby on Rails Performance Tuning. Make it faster, make it better (WindyCityRa...
PPTX
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigue
PDF
Understanding progressive enhancement - yuiconf2010
PDF
Front-End Modernization for Mortals
PDF
Front end-modernization
PDF
Front end-modernization
PPTX
Developing high performance and responsive web apps using web worker
PPTX
Grails and Ajax
Maintainable Javascript carsonified
Magento performancenbs
Web performance
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
Natural Laws of Software Performance
Developing For The Web
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications
Performace optimization (increase website speed)
Web Speed And Scalability
Why test with flex unit
Windy cityrails performance_tuning
Ruby on Rails Performance Tuning. Make it faster, make it better (WindyCityRa...
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigue
Understanding progressive enhancement - yuiconf2010
Front-End Modernization for Mortals
Front end-modernization
Front end-modernization
Developing high performance and responsive web apps using web worker
Grails and Ajax

More from kaven yan (10)

PDF
我的工作态度+@口碑网
PDF
我的工作态度@口碑网
PDF
工作指南@口碑网
PDF
From YUI3 to K2
PDF
HTML5@电子商务.com
PDF
Http协议(rfc2616)中文版
PDF
互联网精神
PDF
理解Ajax性能
PDF
拆分初始化负载
PDF
前端性能优化和自动化
我的工作态度+@口碑网
我的工作态度@口碑网
工作指南@口碑网
From YUI3 to K2
HTML5@电子商务.com
Http协议(rfc2616)中文版
互联网精神
理解Ajax性能
拆分初始化负载
前端性能优化和自动化

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
KodekX | Application Modernization Development
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Electronic commerce courselecture one. Pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
Machine learning based COVID-19 study performance prediction
“AI and Expert System Decision Support & Business Intelligence Systems”
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KodekX | Application Modernization Development
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx

Ajax Performance

  • 1. JavaScript: The Good Parts Part Six: Ajax Performance Douglas Crockford [email_address]
  • 3. The Sessionless Web Cookies for pseudosessions. Cookies enable CSRF attacks. Every action results in a page replacement. Pages are heavy, complicated, multipart things. The web is a big step backwards in individual productivity.
  • 4. “ When your only tool is a hammer, every problem looks like a webpage.”
  • 5. The Ajax Revolution The page is an application with a data connection to a server.
  • 6. When the user does something, we send a JSON message to the server, and receive a JSON message as the result.
  • 7. A JSON message is less work for the server to generate, moves faster on the wire, and is less work for the browser to parse and render than an HTML document.
  • 8.  
  • 9.  
  • 10.  
  • 11.  
  • 12.  
  • 13.  
  • 14.  
  • 15.  
  • 16.  
  • 17.  
  • 18. Division of Labor How is the application divided between the browser and the server?
  • 19. Pendulum of Despair Server The browser is a terminal.
  • 20. Pendulum of Despair Server Browser The browser is a terminal The server is a file system.
  • 21. Seek the Middle Way. A pleasant dialogue between specialized peers.
  • 22. Ajaxify The client and server are in a dialog. Make the messages between them as small as possible. The client does not need a copy of the database. It just needs, at any moment, just enough information to serve the user. Don't rewrite the server application in JavaScript!
  • 23. The Poor Browser The browser is a very inefficient application platform. If your application becomes bloated, performance will be very bad. Try to keep the client programming light.
  • 24. Amazingly, the browser works But it doesn't work well. It is a difficult platform to work with. There are significant security problems. There are significant performance problems. It was not designed to be an application delivery system. Ajax pushes the browser really hard.
  • 25. Correctness First Do not worry about optimization until you have the application working correctly. If it isn’t right, it doesn’t matter if it is fast. Test for performance early. Test in customer configurations: Slow networks, slow computers. Internal networks and developer-class machines can mask performance problems.
  • 26. Premature optimization is the root of all evil. — Donald Knuth Use YSlow to reduce startup time. Don't optimize until you need to, but find out as early as possible if you need to. Clean, correct code is easier to optimize. Tweaking is usually ineffective. Sometimes restructuring or redesign is required.
  • 27. Example var fibonacci = function (n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); }; fibonacci(40) Calls itself 331,160,280 times.
  • 28. Memoizer var memoizer = function (memo, fundamental) { var shell = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; };
  • 29. Memoizer var fibonacci = memoizer([0, 1], function (recur, n) { return recur(n - 1) + recur(n - 2); }); fibonacci(40) Calls itself 38 times. The key to optimization is work avoidance.
  • 30. Code Quality High quality code is most likely to avoid platform problems. Code Conventions for the JavaScript Programming Language http://javascript.crockford.com/code.html Use JSLint.com. Pass with no warnings.
  • 31. Have regular code readings. Don’t wait until release to do code reviews. Do team code reading regularly during development. Experienced developers can lead by example. Novice developers learn from the group. Problems can be discovered early. Good techniques can be shared early.
  • 32. Two Kinds of Optimization Streamlining Algorithm replacement Work avoidance Code removal These things are always good to do Special Casing Adds cruft, increases code size Should only be done when proven necessary
  • 33. Avoid unnecessary displays or animation. Everything costs. Wow costs. As the number of widgets on the page increases, overall ongoing performance gets worse.
  • 34. Only speed up things that take a lot of time. Speeding up things that take very little time will yield very little improvement.
  • 35. Only speed up things that take a lot of time. If profiling shows that you are spending most of your time in A, don't bother optimizing C. A B C D
  • 36. Improving performance If JavaScript were infinitely fast, most pages would run at about the same speed. The bottleneck tends to be the DOM interface. There is a significant cost every time you touch the DOM tree. Each touch can result in a reflow computation, which is expensive.
  • 37. Touch lightly It is faster to manipulate new nodes before they are attached to the tree. Touching unattached nodes avoids the reflow cost. Setting innerHTML does an enormous amount of work, but browsers are really good at it, and it only touches the DOM once.
  • 38. Make good use of Ajax Libraries Effective code reuse will make widgets more effective.
  • 39. How IE8 Spends Its Time Average time allocation of the Alexa 100: Layout 43.16% Rendering 27.25% HTML 2.81% Marshalling 7.34% DOM 5.05% Format 8.66% JScript 3.23% Other 2.5%
  • 40. How IE8 Spends Its Time Opening a thread in GMail: Layout 9.41% Rendering 9.21% HTML 1.57% Marshalling 7.85% DOM 12.47% Format 38.97% JScript 14.43% Other 3.72%
  • 41. Coding Efficiency Common subexpression removal. Loop invariant removal. Most compilers in most programming languages do these optimizations for you. But not JavaScript.
  • 42. Before var i; for (i = 0; i < divs.length ; i += 1) { divs[i].style. color = &quot;black&quot;; divs[i].style. border = thickness + 'px solid blue' ; divs[i].style. backgroundColor = &quot;white&quot;; }
  • 43. After var border = thickness + 'px solid blue' , nrDivs = divs.length , ds , i; for (i = 0; i < nrDivs ; i += 1) { ds = divs[i].style ; ds .color = &quot;black&quot;; ds .border = border ; ds .backgroundColor = &quot;white&quot;; }
  • 44. Strings Concatenation with + Each operation allocates memory foo = a + b; Concatenate with array .join('') The contents of an array are concatenated into a single string foo = [a, b].join('');
  • 45. Don't Tune For Quirks Some browsers have surprising inefficiencies. A trick that is faster on Browser A might be slower on Browser B. The performance characteristics of the next generation may be significantly different. Avoid short-term optimizations.
  • 46. Don't Optimize Without Measuring Intuitions are often wrong. start_time = new Date().valueOf(); code_to_measured(); end_time = new Date().valueOf(); elapsed_time = end_time - start_time; A single trial is unreliable. Timers can be off by as much as 15 msec. Even accurate measurements can lead to wrong conclusions.
  • 47. O (1) An operation that is performed only once is not worth optimizing.
  • 48. O ( n ) An operation that is performed many times may be worth optimizing. Time n Slope: Time per Iteration Fixed time: Startup and cleanup
  • 49. The Axis of Error Inefficiency Time n Inefficiency
  • 50. The Axis of Error Frustration Time n Frustration
  • 51. The Axis of Error Failure Time n Failure
  • 52. O ( n ) Time n Slope: Time per Iteration
  • 53. O ( n log n ) Time n
  • 54. O ( n 2 ) Generally not suitable for browser applications except when n is very small. Time n
  • 55. The most effective way to make programs faster is to make n smaller. Ajax allows for just-in-time data delivery.