function createClosure(one, two) {
let result = null;
return {
compute() {
result = one * two * one * two;
},
printResult() {
console.log(result)
}
}
}
const amt = 200;
let contents = new Array(amt);
for (let i = 0; i < amt; i ++) {
contents[i] = createClosure(Math.random(), Math.random());
contents[i].compute();
contents[i].printResult();
}
class MyClass {
result = null;
constructor(one, two) {
this.one = one;
this.two = two;
}
compute() {
this.result = this.one * this.two * this.one * this.two;
}
printResult() {
console.log(this.result);
}
}
const amt = 200;
let contents = new Array(amt);
for (let i = 0; i < amt; i ++) {
contents[i] = new MyClass(Math.random(), Math.random());
contents[i].compute();
contents[i].printResult();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
closures | |
classes |
Test name | Executions per second |
---|---|
closures | 339.2 Ops/sec |
classes | 219.7 Ops/sec |
I'll break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of two approaches to create and execute code: closures (using a function) versus classes (using a class definition).
Options Compared
createClosure
function takes two parameters (one
and two
) and returns an object with two methods: compute()
and printResult()
. The closure captures the values of one
and two
by value, so they are preserved even when the outer function is executed.MyClass
class has two instance variables (one
and two
) and two methods: compute()
and printResult()
. The class definition uses the this
keyword to access its own scope.Pros and Cons of Each Approach
Library and Special JS Features
There are no libraries used in this benchmark, but I can explain some common JavaScript features that might be relevant:
createClosure
function is a traditional function definition.Other Considerations
When choosing between closures and classes for creating code execution units, consider the following:
Alternatives
If you're interested in exploring alternative approaches to closures and classes, consider the following:
Keep in mind that these alternatives may require additional context and expertise to effectively apply.