Your SlideShare is downloading. ×
0
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Js memory
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Js memory

2,018

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,018
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
28
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. JavaScript MemoryManagementMemory LifecycleJavaScript Garbage CollectorCommon Memory LeaksLeak Detection Tools andTechniquesMinimizing Memory FootprintWednesday, May 29, 13
  • 2. Memory Leaks ? But It’s JS ...Wednesday, May 29, 13
  • 3. Web Applications Are Not Web Sites• Applications maintain state• Applications are more device-specific (fixed sizes andimages)• Applications use devicecapabilities• Applications focus on UXWednesday, May 29, 13
  • 4. Web Applications Are Not Web SitesProvideInformation Provide UXWednesday, May 29, 13
  • 5. Web applications are longrunning processesWednesday, May 29, 13
  • 6. JavaScript Memory• JS Objects take memory• Changing an HTML page clears all memory• Web Apps without proper care => memory related bugsWednesday, May 29, 13
  • 7. When You Have aMemory ProblemApp turns from this...Wednesday, May 29, 13
  • 8. When You Have aMemory Problemto this...Wednesday, May 29, 13
  • 9. How Much Memory Does My Page Use ?Wednesday, May 29, 13
  • 10. How Much Memory Does My Page Use ?Wednesday, May 29, 13
  • 11. MemoryManagement Theory• 3 types of memory managers:• Explicit (C/C++ style)• Reference Count (Perl,Python, PHP)• Garbage Collection (Java,JavaScript)Wednesday, May 29, 13
  • 12. Memory Lifecycle• All languages are the same:• (1) Allocate some memory• (2) Use that memory• (3) Free that memory• In JS, #3 is implicitWednesday, May 29, 13
  • 13. Memory Is Allocated When You Define Literalsvar n = 123;var s = "azerty";var o = {a: 1,b: null};var a = [1, null, "abra"];function f(a){return a + 2;}someElement.addEventListener(click, function(){someElement.style.backgroundColor = blue;}, false);Wednesday, May 29, 13
  • 14. Hidden Memory Allocationsvar d = new Date();var e = document.createElement(div); // allocates an DOMelementvar s = "foo";var s2 = s.substr(0, 3); // s2 is a new stringvar a = ["ouais ouais", "nan nan"];var a2 = ["generation", "nan nan"];var a3 = a.concat(a2);Wednesday, May 29, 13
  • 15. Releasing Memory• JavaScript uses Mark-And-Sweep garbage collection algorithm• It starts from known memory (global object)• Follows all references• In the end, clear the unreachableWednesday, May 29, 13
  • 16. Memory Leak• Object is allocated• Object can’t be reached• Object still uses memory• Impossible in JavaScriptWednesday, May 29, 13
  • 17. A JavaScript Memory Problem is caused by usingtoo much memoryWednesday, May 29, 13
  • 18. Objects GraphPrimitivetypesGlobalObjectRetainingObjectsWednesday, May 29, 13
  • 19. Objects GraphPrimitivetypesGlobalObjectRetainingObjectsGarbageWednesday, May 29, 13
  • 20. Cleaning Up MemoryAn object is released when:garbage collector runsANDthat object is unreachableWednesday, May 29, 13
  • 21. Common MemoryErrors• Primitive Types• Arrays• Objects• Functions• Detached DOM Nodes• Multiple Function CopiesWednesday, May 29, 13
  • 22. Primitive Types• Number, Boolean, Null or Undefined• Can’t cause memory problems - size is limited• Each variable holds a single objectWednesday, May 29, 13
  • 23. String Variables• Unbound strings lead to memory problems• Review the program below. Can you spot the bug ?var text = "";setInterval(function() {$.get(/page.html, function( data ) {text += data;$(#main).html( text );});}, 2000);Wednesday, May 29, 13
  • 24. String Variables• Variable text is appended to again and again• It will take more memory as time goes• A better way: Use .appendChild(...) or $(...).append(...)Wednesday, May 29, 13
  • 25. Arrays• Arrays are retaining objects• Memory Errors:• Hidden Allocations• Unbound ArraysWednesday, May 29, 13
  • 26. Hidden Array Allocations• The following functions create new arrays:• [...]• new Array(...)• slice(...)• map(...)• filter(...)• concat(...)Wednesday, May 29, 13
  • 27. Unbound Arrays• Unbound arrays are such that can grow ad infinitum• Example:• Keep high score in a game• Show top 10 scoreWednesday, May 29, 13
  • 28. Unbound Arraysvar all_score = [];function add_score( score ) {all_score.push( score );}function top_10() {return all_score.sort(function(a, b) { return b - a }).slice(0, 10);}all_score is unboundWednesday, May 29, 13
  • 29. Objects• Same as with arrays• Unbound objects are dangerous• Example:• Keep a cache of user details based on data from serverWednesday, May 29, 13
  • 30. Objectsvar users = {};function getUserDetails( user_id, cb ) {if ( ! users[user_id] ) {$.get(/users/ + user_id, function( info ) {users[user_id] = info;cb( info );});} else {setTimeout( cb, 0, users[user_id] );}}Wednesday, May 29, 13
  • 31. Objectsvar users = {};function getUserDetails( user_id, cb ) {if ( ! users[user_id] ) {$.get(/users/ + user_id, function( info ) {users[user_id] = info;cb( info );});} else {setTimeout( cb, 0, users[user_id] );}}Unbound ObjectWednesday, May 29, 13
  • 32. Functions• Functions retain other objects in a different way• Static retainment / Closures• Danger: Closures are hard to detectWednesday, May 29, 13
  • 33. Functionsfunction make_double() {var x = 5;var y = 7;return function(z) {return z * z;};}Wednesday, May 29, 13
  • 34. Functionsfunction make_double() {var x = 5;var y = 7;return function(z) {return z * z;};}var f = make_double();inner function retainsboth x and yWednesday, May 29, 13
  • 35. Q & AWednesday, May 29, 13
  • 36. Detached DOM Nodes• DOM nodes are objects too• JavaScript can take a handle to DOM nodes with:• getElementById• getElementsByTagName• querySelector / querySelectorAll• DOM frameworksWednesday, May 29, 13
  • 37. Detached DOM Nodes<html><body><p>Hello World</p><div><img src="example.png"/></div></body></html>Wednesday, May 29, 13
  • 38. Detached DOM Nodes<html><body><p>Hello World</p><div><img src="example.png"/></div></body></html>var img = document.querySelector("img")Wednesday, May 29, 13
  • 39. Detached DOM Nodes• DOM Nodes are node deleted until all handles to them are out of scope• If removed from DOM, they are called Detached nodes• Event handlers are also handlesWednesday, May 29, 13
  • 40. Example: Detached DOM Nodesvar btn = document.querySelector(button);var counter = 10;var div = document.querySelector(div);btn.addEventListener(click, function() {if ( counter < 0 ) return;counter -= 1;div.innerHTML = counter;if ( counter == 0 ) {div.parentElement.removeChild(div);}});Wednesday, May 29, 13
  • 41. Example: Detached DOM Nodes• The variable div is a DOM node handle• It retains the HTMLDivElement even after its removal• Since div is global, the node will never be releasedWednesday, May 29, 13
  • 42. Detached DOM Nodes: Takeaways• Use lexicals• Watch out for every DOM handleWednesday, May 29, 13
  • 43. Multiple Function Copies• A common JavaScript class pattern looks like thisvar Person = function() {var self = this;self.hi = function() {console.log(Hello World!);};self.grow_up = function() {self.age += 1;};self.age = 0;};Wednesday, May 29, 13
  • 44. Multiple Function Copies• How many objects are created ?for ( var i=0; i < 10; i++ ) {new Person();}Wednesday, May 29, 13
  • 45. Multiple Function Copies• Each new creates:• An object• An age (number)• Two functions: hi and grow_upWednesday, May 29, 13
  • 46. Common Solution: Prototypes• Prototypes allow storing actions in a shared object• All objects that share the prototype will have these actionsp1 p2 p3p_protoage age agegrow_uphiWednesday, May 29, 13
  • 47. Solving With Prototypesvar PersonActions = {hi: function() {console.log(Hello World!);},grow_up: function() {this.age += 1;}};var Person = function() {var self = this;self.age = 0;};Person.prototype = PersonActions;Wednesday, May 29, 13
  • 48. Using Prototypes• Prototypes are confusing• Developers mistake them for inheritance (which they’re not)• Developers store data in prototypes (which they shouldn’t)• Prototypes force us to use this• Use prototypes wiselyWednesday, May 29, 13
  • 49. Q & AWednesday, May 29, 13
  • 50. Tools For Memory Management• Chrome Task Manager,available from:• Tools->Task Manager• If memory tab is hidden, turn iton via context menuWednesday, May 29, 13
  • 51. Tools For Memory Management• Chrome Memory Timeline• Available from Developer ToolsWednesday, May 29, 13
  • 52. Tools For Memory Management• Chrome Heap Profiler• Available from Developer ToolsWednesday, May 29, 13
  • 53. Lab 01• There’s a memory leak in the following code:https://gist.github.com/ynonp/4742321• And this one:https://gist.github.com/ynonp/4749795• What is leaking ?• What’s causing the leak ?• Fix It !Wednesday, May 29, 13
  • 54. Lab 02• The following program leaks memory:https://github.com/ynonp/advanced-fed-examples/tree/master/memory/lab02• What is leaking ? Why ?• Fix it !Wednesday, May 29, 13
  • 55. JavaScript Memory TakeawaysWednesday, May 29, 13
  • 56. “We should forget about small efficiencies, sayabout 97% of the time: premature optimization isthe root of all evil”— Donald KnuthWednesday, May 29, 13
  • 57. Optimization Done Right• Verify memory problem using Chrome Task Manager• Find hurting procedure using Chrome Memory Profiler• Find buggy code using Chrome Heap SnapshotWednesday, May 29, 13
  • 58. Cleaning Up Memory• Avoid global variables• A global is NEVER freed• A lexical is freed when out-of-scopeWednesday, May 29, 13
  • 59. Limit Cache SizeWednesday, May 29, 13
  • 60. Keep an eye on detached DOM nodes• Caching DOM nodes helps performance• If they are removed, memory is leaked• To be specific:• this.el = document.querySelector(#my-list);Wednesday, May 29, 13
  • 61. Keep an eye on event handlers$(window).on(resize,function() {img.css(...);});Retains img foreverWednesday, May 29, 13
  • 62. Avoid old IE (but if you must, use jQuery)Wednesday, May 29, 13
  • 63. Thanks For Joining• Slides By:• Ynon Perek• ynon@ynonperek.com• http://ynonperek.com• Free photos from:• 123rf.com• http://morguefile.comWednesday, May 29, 13

×