var arr = [];
function functionDeclaration(item) {
arr.push(item);
}
for (let i = 1; i < 10000; i++) {
functionDeclaration(i);
}
var functionExpression = function(item) {
arr.push(item);
};
for (let i = 1; i < 10000; i++) {
functionExpression(i);
}
class Test {
constructor(item) {
this.item = item;
}
addItem(){
arr.push(this.item)
}
}
for (let i = 1; i < 10000; i++) {
new Test(i).addItem();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
function declaration | |
function expression | |
class |
Test name | Executions per second |
---|---|
function declaration | 1460.6 Ops/sec |
function expression | 1417.2 Ops/sec |
class | 509.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test that compares three different approaches to achieve the same goal: pushing items onto an array.
Approaches being compared:
function foo(item) { arr.push(item); }
) and calls it repeatedly.const bar = function(item) { arr.push(item); };
) and calls it repeatedly.class MyClass { constructor(item) { this.item = item; } addItem() { arr.push(this.item); } }
) and creates instances of the class, calling the addItem()
method.Pros and Cons:
Library usage: None of the approaches explicitly use a library. However, it's worth noting that some browsers (e.g., V8 in Chrome) have optimized implementations for certain JavaScript constructs, like closures or function declarations.
Special JS feature or syntax: None mentioned.
Now, let's look at the benchmark results:
The top result shows that Function Expression outperforms the other two approaches on this particular test case, with an execution rate of 1876.09 executions per second. The middle result indicates that Function Declaration is slightly slower than Function Expression but faster than Class. The bottom result shows that Class is the slowest approach in this benchmark.
If you're interested in exploring alternative approaches or optimizing your own JavaScript performance, here are some additional considerations:
For a broader perspective on JavaScript benchmarking and optimization, you might want to explore other resources, such as: