var arr = [];
var classInstances = [];
var functionInstances = [];
var numInstances = 100000;
function addItem(item) {
arr.push(item);
};
class TestClass {
constructor() {
}
addItem(item){
this.item = item;
arr.push(this.item)
}
}
function TestFunction() {
}
TestFunction.prototype.addItem = function(item) {
this.item = item;
arr.push(item)
}
for( var i = 0; i < numInstances; i++ ) {
classInstances[i] = new TestClass();
functionInstances[i] = new TestFunction();
}
arr.length = 0;
for (var i = 0; i < numInstances; i++) {
addItem(i);
}
arr.length = 0;
for (var i = 0; i < numInstances; i++) {
classInstances[i].addItem(i);
}
arr.length = 0;
for (var i = 0; i < numInstances; i++) {
functionInstances[i].addItem(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
pure function | |
class method | |
function method |
Test name | Executions per second |
---|---|
pure function | 83.5 Ops/sec |
class method | 78.3 Ops/sec |
function method | 81.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark measures the performance difference between three approaches:
Options Compared
The benchmark compares the performance of these three approaches in terms of:
Pros and Cons
Library and Special JS Features
In this benchmark, no external libraries are used. However, note that if you were to extend or modify the test cases, you might need to consider using libraries like Lodash
for utility functions or ES6 Promises
for handling asynchronous operations.
No special JavaScript features are explicitly mentioned in the benchmark definition or test cases.
Alternative Approaches
If you're looking for alternative approaches to this benchmark, consider:
map
or forEach
to manipulate arrays could be compared to pure functions and class methods.When evaluating these alternatives, keep in mind the specific use case and requirements of your project.
I hope this explanation helps you understand the benchmark and its underlying mechanics!