public
Created

  • Download Gist
obj-gc-test-fail.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// run with "node --expose_gc"
 
var weak = require('weak')
, util = require('util')
 
function MyObject () {
var self = this;
Object.defineProperty(this, 'color', {
get: function() { return 'red' }
})
setTimeout(function () {
self.emit('close')
}, 2000)
}
 
util.inherits(MyObject, process.EventEmitter)
 
var count = 0
, countGc = 0
 
for (var i = 0; i < 1000; i++) {
var o = new MyObject()
count++
o.on('close', function () { count--})
countGc++
weak(o, function () { countGc-- })
}
 
setInterval(function () {
gc()
console.log('objects: %d, garbage collected: %d', count, countGc)
}, 1000)
obj-gc-test-pass.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// run with "node --expose_gc"
 
var weak = require('weak')
, util = require('util')
 
function MyObject () {
var self = this;
this.color = 'red'
setTimeout(function () {
self.emit('close')
}, 2000)
}
 
util.inherits(MyObject, process.EventEmitter)
 
var count = 0
, countGc = 0
 
for (var i = 0; i < 1000; i++) {
var o = new MyObject()
count++
o.on('close', function () { count--})
countGc++
weak(o, function () { countGc-- })
}
 
setInterval(function () {
gc()
console.log('objects: %d, garbage collected: %d', count, countGc)
}, 1000)
output-fail.txt
1 2 3 4 5 6 7 8 9 10 11
objects: 1000, garbage collected: 1000
objects: 1000, garbage collected: 1000
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
objects: 0, garbage collected: 12
...
output-pass.txt
1 2 3 4 5 6 7 8 9 10 11
objects: 1000, garbage collected: 1000
objects: 1000, garbage collected: 1000
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
objects: 0, garbage collected: 0
...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.