function func(v) {
const instance = { a: v }
instance.b = function() {
return instance.a
}
return instance
}
for (let i = 0; i < 100; i++) {
const instance = func(i)
instance.b()
instance.b()
instance.b()
instance.b()
instance.b()
}
class Class {
constructor(v) {
this.a = v
this.b = function() {
return this.a
}
}
}
for (let i = 0; i < 100; i++) {
const instance = new Class(i)
instance.b()
instance.b()
instance.b()
instance.b()
instance.b()
}
function Func(v) {
this.a = v
this.b = function() {
return this.a
}
}
for (let i = 0; i < 100; i++) {
const instance = new Func(i)
instance.b()
instance.b()
instance.b()
instance.b()
instance.b()
}
function func() {
return this.a
}
class Class {
constructor(v) {
this.a = v
this.b = func
}
}
for (let i = 0; i < 100; i++) {
const instance = new Class(i)
instance.b()
instance.b()
instance.b()
instance.b()
instance.b()
}
function func(v) {
let a = v
function b() {
return a
}
return { b }
}
for (let i = 0; i < 100; i++) {
const instance = func(i)
instance.b()
instance.b()
instance.b()
instance.b()
instance.b()
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
function instance | |
new Class | |
new Function | |
new Class singletone function | |
function lexical |
Test name | Executions per second |
---|---|
function instance | 814419.3 Ops/sec |
new Class | 111140.0 Ops/sec |
new Function | 113115.6 Ops/sec |
new Class singletone function | 113687.3 Ops/sec |
function lexical | 1004202.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark compares the performance of three approaches: creating a function instance, using a class with an instance method, and using a Function constructor. The test cases are designed to measure the execution speed of each approach by calling the instance method 10 times in a loop.
Options Compared
function
keyword.Function
constructor to create a new function instance.Pros and Cons
Library Usage
None of the test cases use external libraries.
Special JS Features or Syntax
The test cases do not explicitly use any special JavaScript features or syntax. However, the Function
constructor is used in one of the test cases, which might be considered a legacy feature.
Benchmark Results
The latest benchmark results show that the Singleton Function approach performs best, followed closely by the Class with Instance Method approach. The Function Instance approach performs relatively poorly.
Other Alternatives
Overall, the benchmark highlights the importance of considering the performance implications of different programming approaches in JavaScript. The test cases demonstrate that even seemingly minor differences in syntax can lead to significant variations in execution speed.