Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JavaScript Timers, Power Consumption, and Performance

35,231 views

Published on

E

Published in: Technology

JavaScript Timers, Power Consumption, and Performance

  1. flickr.com/photos/barbourians/6662357209/ Timers, Power Consumption, and PerformanceNicholas C. ZakasChief Architect, WellFurnished
  2. New
  3. @slicknet (Complaints: @souders)
  4. UI Thread ExecuteUpdate UI JavaScript flickr.com/photos/jepoirrier/954701212/
  5. flickr.com/photos/55733754@N00/3325000738/
  6. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ //do something };};</script>
  7. Before ClickUI Threadtime UI Queue
  8. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
  9. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
  10. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
  11. When ClickedUI Thread Update UI onclick Update UItime UI Queue Draw up state
  12. No UI updates while JavaScript is executing
  13. JavaScript May Cause UI Update<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ var div = document.createElement("div"); div.className = "tip"; div.innerHTML = "You clicked me!"; document.body.appendChild(div); };};</script>
  14. Each UI update appliesALL CHANGES since the last UI update
  15. I gonna make anamination!! flickr.com/photos/oakleyoriginals/3065393607/
  16. function naminate(element){ // start here element.style.left = "10px"; // move to here element.style.left = "30px"; // then to here element.style.left = "50px"; // finally to here element.style.left = "70px";}
  17. Whyyou nowork???flickr.com/photos/tudor/318123668/
  18. function namimate(element){ // start here element.style.left = "10px"; // move to here element.style.left = "30px"; // then to here element.style.left = "50px"; Last state // finally to here wins element.style.left = "70px";}
  19. setTimeout()
  20. Code to executevar tId = setTimeout(function(){ // do something Delay in}, 1500); milliseconds// optionalclearTimeout(tId)
  21. setTimeout() DOES NOT SAY“Run this code after this delay”
  22. setTimeout() DOES SAY“Add this code to the queue after this delay”
  23. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ setTimeout(function() { //do something }, 25); };};</script>
  24. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
  25. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
  26. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
  27. When ClickedUI Thread Update UI onclick Update UItime UI Queue Draw up state
  28. After 25msUI Thread Update UI onclick Update UItime UI Queue JavaScript Added to back of queue
  29. FutureUI Thread Update UI onclick Update UI JavaScripttime UI Queue
  30. FutureUI Thread Update UI onclick Update UI JavaScripttime UI Queue Update UI If the JavaScript changes the UI, it triggers another update
  31. setTimeout() sends your code into the future
  32. setTimeout(function(){ element.style.left = "10px";}, 50);setTimeout(function(){ element.style.left = "30px";}, 100);setTimeout(function(){ element.style.left = "50px";}, 150);setTimeout(function(){ element.style.left = "70px";}, 200);
  33. Animation Loop(function(){ var delay = 100; function moveTheThing(){ // actually move the thing setTimeout(moveTheThing, delay); } setTimeout(moveTheThing, delay);}());
  34. (function(){ var msg = "Some reasonably long text that keeps scrolling.", len = 25, pos = 0, padding = msg.replace(/./g, " ").substr(0,len) finalMsg = padding + msg, delay = 100; function updateText(){ var curMsg = finalMsg.substr(pos++, len); window.status = curMsg; if (pos == finalMsg.length){ pos = 0; } setTimeout(updateText, delay); } setTimeout(updateText, delay);}());
  35. And More!
  36. setTimout() all the things!!!
  37. Problems
  38. The default system-wide timer resolution in Windows is 15.6 ms, whichmeans that every 15.6 ms the operating system receives a clock interruptfrom the system timer hardware.-Timers, Timer Resolution, and Development of Efficient Code (Microsoft)
  39. var tId = setTimeout(function(){ // do something}, 10); What does it mean?
  40. http://ejohn.org/blog/accuracy-of-javascript-time/
  41. Animation Loop(function(){ var delay = 17; Pretty function moveTheThing(){ please?!?! // actually move the thing setTimeout(moveTheThing, delay); } setTimeout(moveTheThing, delay);}());
  42. http://ejohn.org/blog/analyzing-timer-performance/
  43. 1ms all the timers!!!
  44. http://www.belshe.com/2010/06/04/chrome-cranking-up-the-clock/
  45. timeBeginPeriod()
  46. timeBeginPeriod(1)
  47. setTimout() all the things!!!
  48. flickr.com/photos/antonfomkin/3046849320/
  49. Modern CPUs are narcoleptic
  50. x86 CPU States C0 Active C1 Halt C2 Stop-Clock C3 SleepLow C4 Deep SleepPower C5 Enhanced Deep Sleep C6 Deep Power Down
  51. http://software.intel.com/en-us/articles/cpu-power-utilization-on-intel-architectures/
  52. CPUs go to sleep when idle
  53. The default timer resolution on Windows 7 is 15.6 milliseconds (ms).Some applications reduce this to 1 ms, which reduces the battery runtime on mobile systems by as much as 25 percent.-Timers, Timer Resolution, and Development of Efficient Code (Microsoft) Laptops!
  54. Web Timer Resolution TodayPlugged In 4ms 4ms 4ms 4ms 4msBattery 4ms 15.6ms 4ms 15.6ms 4msBackground 1s 1s 4ms 1s* 4ms * Internet Explorer 10
  55. Web Timer Resolution TodayBattery 4ms 10ms 10ms 10ms 4msBackground Tab - 10ms 10ms 10ms 1sBackground App - * * * 1s * “Catches up” when switched back
  56. Experiment• Hard shutdown and restart so no other apps are running• Turn off brightness auto-adjust• Turn off screen locking• Leave WiFi/Mobile on• Load test page in browser• Profit!
  57. Experiment• Test single timer at different intervals: • 1000ms – 10ms
  58. Low Frequency >= 1000msHigh Frequency < 1000ms
  59. Time For 10% Power Use By FrequencyMinutes 52-56 42-48 62-65
  60. Timer frequency doesn’t matter
  61. http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html
  62. Experiment• Test single timer at different intervals: • 1000ms – 10ms• Test multiple timers at different intervals • 1000ms – 10ms x 10
  63. Time For 10% Power Use By Count (same)Minutes 52-56 42-48 62-65
  64. Number of timers doesn’t matter
  65. Number of timers does matter (accuracy)
  66. http://ejohn.org/apps/timers
  67. http://ejohn.org/apps/timers
  68. http://ejohn.org/apps/timers
  69. Flooding the QueueUI Threadtime UI Queue timer timer timer
  70. Too many timers affects rendering
  71. Elsewhere…
  72. http://www.w3.org/TR/css3-animations/
  73. Optimized animations using CSS
  74. div { animation-name: diagonal-slide; animation-duration: 5s; animation-iteration-count: 10;}@keyframes diagonal-slide { Hey browser! from { I’m animating! left: 0; top: 0; } to { left: 100px; top: 100px; } }
  75. Hey browser! I want to dovar tId = setTimeout(function(){ something // do something later}, 1500); Could be animation. Could be polling. Don’t sweat it.
  76. http://www.w3.org/2010/webperf/
  77. moz webkithttp://www.w3.org/TR/animation-timing/
  78. Code to executevar rId = requestAnimationFrame(function(time){ // do something});// optional Time whenclearAnimationFrame(rId) the paint will happen
  79. New Animation Loop(function(){ function moveTheThing(){ Hey browser! I’m animating! // actually move the thing requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
  80. New Animation Loop(function(){ var element = document.getElementById("box"); function moveTheThing(){ element.style.left = (element.offsetLeft + 5) + "px"; requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
  81. New Animation Loop(function(){ var element = document.getElementById("box"), start = Date.now(); function moveTheThing(time){ var since = (time || Date.now()) – start; element.style.left = (element.offsetLeft + since)+ "px"; requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
  82. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ requestAnimationFrame(function() { //do something }); };};</script>
  83. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
  84. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
  85. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
  86. Call to requestAnimationFrame()UI Thread Update UI onclicktime UI Queue Update UI Changes Anim Frame
  87. When ClickedUI Thread Update UI onclick Update UItime UI Queue Changes Draw up state Anim Frame
  88. Before Next FrameUI Thread Update UI onclick Update UI Changestime UI Queue Anim Frame
  89. Naminate!UI Thread Update UI onclick Update UI Changes Anim Frametime UI Queue Draw whatever changes are necessary
  90. [requestAnimationFrame()’s framerate is] capped at 1000/(16 + N)fps, where N is the number of ms it takes your callback to execute.If your callback takes 1000ms to execute, then its capped at under1fps. If your callback takes 1ms to execute, you get about 60fps.-Boris Zbarsky (Mozilla) via Paul Irish (Google)
  91. Animate all the things!!! …with CSS and requestAnimationFrame
  92. What about other things?
  93. https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
  94. Code to executevar iId = setImmediate(function(){ // do something msSetImmediate()}); msClearImmediate()// optionalclearImmediate(iId)
  95. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ setImmediate(function() { //do something }); };};</script>
  96. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
  97. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
  98. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
  99. Call to setImmediate()UI Thread Update UI onclicktime UI Queue Update UI Changes Always added after the last UI update in the queue
  100. When ClickedUI Thread Update UI onclick Update UItime UI Queue Changes Draw up state
  101. Immediately!UI Thread Update UI onclick Update UI Changestime UI Queue
  102. https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
  103. http://www.w3.org/TR/workers/
  104. //in pagevar worker = new Worker("process.js");worker.onmessage = function(event){ useData(event.data);};worker.postMessage(values);
  105. //in process.jsself.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){ process(items[i]); } self.postMessage(items);};
  106. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
  107. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
  108. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
  109. Create Web WorkerUI Thread Update UI onclicktime UI Queue Update UI Creates a backgroundthread/process/etc.
  110. postMessage()UI Thread Update UI onclick Update UItime UI Queue process
  111. Worker CompleteUI Thread Update UI onclick Update UItime UI Queue onmessage
  112. FutureUI Thread Update UI onclick Update UI onmessagetime UI Queue
  113. Recommendations
  114. • Use as few as necessary Timers • If multiple are necessary, use a single timer that can accommodate allAnimation • Use CSS transitions and animations first • If not possible, use requestAnimationFrame() Other • Use web workers for efficient data processing • If no other options, use timers (see first point)
  115. EtceteraMy company: • wellfurnished.com My blog: • nczonline.net Twitter • @slicknetThese Slides: • slideshare.net/nzakas

×