Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@patoi
Last active June 14, 2019 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patoi/5798bb3e0f2d9dff7ae7db80739dbaa3 to your computer and use it in GitHub Desktop.
Save patoi/5798bb3e0f2d9dff7ae7db80739dbaa3 to your computer and use it in GitHub Desktop.
'use strict'
const ITERATION = 1000
console.log(
process.version,
ITERATION,
'iteration',
'with Type and freeze – v2: prototype based constructor function'
)
/**
* Type enumeration.
* @readonly
* @enum {string}
*/
const Type = {
/** Homo sapiens sapiens */
HUMAN: 'HUMAN',
/** brrr... zz... */
ROBOT: 'ROBOT'
}
Object.freeze(Type)
// closure function test
const Human = () => {
const _type = [Type.HUMAN]
let _name
let _iq
return {
setIQLevel (iq) {
_iq = iq
return this
},
getIQLevel () {
return _iq
},
setName (name) {
_name = name
return this
},
getName () {
return _name
},
getType () {
return _type
},
get () {
return {
type: _type,
iq: this.getIQLevel(),
name: this.getName()
}
}
}
}
let i = 0
let SarahConnor
let start = process.hrtime.bigint()
while (i < ITERATION) {
SarahConnor = Human()
.setName('Sarah Connor')
.setIQLevel(154)
i++
}
let end = process.hrtime.bigint()
let closureExampleTime = end - start
// console.log('Sarah Connor:', SarahConnor.get())
// constructor function test
function Human2 ({ iq, name }) {
this.iq = iq
this.name = name
this.type = [Type.HUMAN]
}
Human2.prototype.setIQLevel = function (iq) {
this.iq = iq
}
Human2.prototype.getIQLevel = function () {
this.iq
}
Human2.prototype.setName = function (name) {
this.name = name
}
Human2.prototype.getName = function () {
return this.name
}
Human2.prototype.getType = function () {
return this.type
}
Human2.prototype.get = function () {
return {
type: this.type,
iq: this.iq,
name: this.name
}
}
i = 0
let JohnConnor
start = process.hrtime.bigint()
while (i < ITERATION) {
JohnConnor = new Human2({ iq: 154, name: 'John Connor' })
i++
}
end = process.hrtime.bigint()
let funcExampleTime = end - start
// console.log('John Connor:', JohnConnor.get())
// class test
class Human3 {
constructor ({ iq, name }) {
this.iq = iq
this.name = name
this.type = [Type.HUMAN]
}
setIQLevel (iq) {
this.iq = iq
}
getIQLevel () {
this.iq
}
setName (name) {
this.name = name
}
getName () {
return this.name
}
getType () {
return this.type
}
get () {
return {
type: this.type,
iq: this.iq,
name: this.name
}
}
}
i = 0
let KatrineBrewster
start = process.hrtime.bigint()
while (i < ITERATION) {
KatrineBrewster = new Human3({ iq: 154, name: 'KatrineBrewster' })
i++
}
end = process.hrtime.bigint()
let classExampleTime = end - start
console.info(
`CL: ${closureExampleTime}, FN: ${funcExampleTime}, CLASS: ${classExampleTime} nanosec.`
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment