function Custom(iterable = null) {
if (iterable !== null) {
this.array = Array.from(iterable);
} else {
this.array = [];
}
this.length = this.array.length;
this.index0 = 0;
}
Custom.prototype.item = function (accessor) {
return this.array[this.index0 + Number(accessor)];
};
Custom.prototype.set = function (index, value) {
const newIndex = this.index0 + Number(index);
if (newIndex >= this.length) {
this.length = newIndex + 1;
}
this.array[newIndex] = value;
};
Custom.prototype.shift = function () {
if (this.length !== 0) {
this.length--;
this.index0++;
return this.array[this.index0 - 1];
}
return undefined;
};
Custom.prototype.pop = function () {
if (this.length !== 0) {
this.length--;
return this.array[this.index0 + this.length];
}
return undefined;
};
Custom.prototype.push = function (value) {
this.array[this.index0 + this.length] = value;
this.length++;
};
function p(array) {
for (var i = 0; i <= 10000000; i++) {
array[array.length] = i;
}
return array;
}
var a1 = p([]);
var a2 = p([]);
var q = new Custom(p(p(p(p(p([]))))));
var s = new Custom(p(p(p(p(p([]))))));
a1.shift();
a2.pop();
q.shift();
s.pop();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Shift | |
Array Pop | |
Custom Shift | |
Custom Pop |
Test name | Executions per second |
---|---|
Array Shift | 1062.8 Ops/sec |
Array Pop | 31789050.0 Ops/sec |
Custom Shift | 16700338.0 Ops/sec |
Custom Pop | 16463451.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the pros and cons of each approach, and other considerations.
Benchmark Overview
The benchmark compares the performance of three implementations:
Array-based Shift/Pop
This implementation uses JavaScript arrays for both shift and pop operations. The pros of this approach include:
However, there are some cons:
Custom non-mutative Stack/Queue
This implementation uses a Custom class with methods for shift, pop, set, item, and push operations. The pros of this approach include:
However, there are some cons:
Comparison
The benchmark tests the execution speed of these three implementations. The results show that:
Other Considerations
When choosing an implementation, consider the following factors:
Alternatives
Other alternatives for implementing stack/queue operations include:
Queue
class or third-party libraries like bull-queue
.Keep in mind that each approach has its trade-offs and may be more suitable depending on the specific requirements of your project.