Skip to content

Instantly share code, notes, and snippets.

@Rob-ot
Created October 26, 2013 19:50
Show Gist options
  • Save Rob-ot/7173723 to your computer and use it in GitHub Desktop.
Save Rob-ot/7173723 to your computer and use it in GitHub Desktop.
Fun with __proto__
# To run:
# npm install -g coffee-script
# npm install usage
# coffee example.coffee
# Let me know if you know of a more memory efficient way that is compatible with IE
_ = require 'lodash'
assert = require 'assert'
usage = require 'usage'
class Num
num: true
class Str
str: true
# changing the class out from under an object using __proto__ - not supported in IE :(
ohs = []
for i in [0..1000000]
do ->
n = new Num()
n.__proto__ = Str.prototype
assert.ok n.str
ohs.push n
# runs in < 1s uses 69MB of memory
# changing the class out from under an object by creating a new Class per object - works everywhere but uses too much memory
ohs = []
for i in [0..1000000]
do ->
Cons = ->
Cons.prototype = _.clone Num.prototype
n = new Cons()
Object.keys(Cons.prototype).forEach (k) ->
delete Cons.prototype[k]
_.extend Cons.prototype, Str.prototype
assert.ok n.str
ohs.push n
# runs in about 5s uses 1091MB of memory
usage.lookup process.pid, (err, result) ->
console.log result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment