Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. let HEAP = [];
  2.  
  3. const A = {
  4. language: 'JavaScript'
  5. };
  6.  
  7. HEAP.push(A);
  8.  
  9. const root = () => HEAP[0];
  10.  
  11. const B = {
  12. language: 'Rust'
  13. };
  14.  
  15. HEAP.push(B);
  16.  
  17. A.B = B;
  18.  
  19. const C = {
  20. language: 'Elm'
  21. };
  22.  
  23. HEAP.push(C);
  24.  
  25. A.C = C;
  26.  
  27. // Let's remove the reference C
  28. delete A.C;
  29.  
  30. const D = {
  31. language: 'GoLang'
  32. };
  33.  
  34. HEAP.push(D);
  35.  
  36. // Object "D" is reachable from "B" and is allocated the memory
  37. B.D = D;
  38.  
  39. // "B" reference is removed from "A".
  40. delete A.B;
  41.  
  42. // It means that "D" still has the reference to it from "B" but it's
  43. // not reachable (because B is not reachable anymore)
  44.  
  45. // After these manipulations, the heap still contains four objects:
  46. // [{ A }, { B }, { C }, { D }], but only the "A" object is reachable (root)
  47.  
  48. // Garbage collector (uses mark and sweep algorithm )
  49. const gc = () => {
  50. // Set __mark__ bits on the reachable objects to 1
  51. mark();
  52.  
  53. // Collect the garbage (objects with __mark__ bit not set to 1)
  54. sweep();
  55. }
  56.  
  57. // Traverse all the reachable objects starting from the root and set the
  58. // __mark__ bit on it to 1
  59. const mark = () => {
  60.  
  61. // Initially only the root is reachable
  62. let reachables = [ root() ];
  63.  
  64. while (reachables.length) {
  65. // Get the next object
  66. let current = reachables.pop();
  67. // Mark the object if it is not already marked
  68. if (!current.__markBit__) {
  69. current.__markBit__ = 1;
  70. // add all the reachable objects from the current object
  71. // reachables array
  72. for (let i in current) {
  73. if (typeof current[i] === 'object') {
  74. // Add it to the reachables
  75. reachables.push(current[i]);
  76. }
  77. }
  78. }
  79. }
  80. }
  81.  
  82.  
  83. // Traverse the heap and move all unmarked or unreachable objects to the free list.
  84. const sweep = () => {
  85. // Update the state
  86. HEAP = HEAP.filter((current) => {
  87. // For future Garbage collection cycles, reset the __markBit__ bit to 0
  88. if (current.__markBit__ === 1) {
  89. current.__markBit__ = 0;
  90. return true;
  91. } else return false; // move it to the free list
  92. });
  93. }
  94.  
  95.  
  96. const main = () => {
  97. console.log("\nHeap state before garbage collection: ", HEAP);
  98.  
  99. // Make a call to garbage collector
  100. gc();
  101.  
  102. console.log("\nHeap state after garbage collection: ", HEAP);
  103. }
  104.  
  105. main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement