我在Javascript中编写了一个堆栈实现,并将其作为节点模块调用' stack-js-implementation'。
您可以在此处查看源代码:
function _StackItem(data, prev, next){
this.data = data;
this.prev = prev;
this.next = next;
}
function Stack(size){
this.maxSize = size;
this.currentSize = 0;
this.head = null;
this.last = null;
}
Stack.prototype.push = function(data){
if (this.head === null) {
var newStackItem = new _StackItem(data, null, null);
this.head = newStackItem;
this.last = newStackItem;
this.currentSize += 1;
}else{
var originalTopStackItem = this.head;
var newStackItem = new _StackItem(data, null, originalTopStackItem);
originalTopStackItem.prev = newStackItem;
this.head = newStackItem;
if (this.currentSize === this.maxSize) {
this.last.prev.next = null;
this.last = this.last.prev;
}else{
this.currentSize += 1;
}
}
};
Stack.prototype.pop = function(){
var topStackItem = this.head;
if (topStackItem === null) {
return this.head;
}
this.currentSize -= 1;
if (topStackItem.next === null) {
this.head = null;
this.last = null;
return topStackItem.data;
}else{
this.head = topStackItem.next;
return topStackItem.data;
}
};
我实现了自己的堆栈数据结构,因为我想限制堆栈大小。如果堆栈已达到最大大小,执行push
将删除堆栈的最底部元素,并将新元素推送到堆栈的最顶部位置。
我认为如果我使用传统阵列,它将花费大量时间进行移动,因此我使用链接列表构建它。
在做了一些测试之后,我发现当大小达到最大大小时,将新元素推送到堆栈时,这个实现比数组更快。
但是在新元素达到最大大小之前将其推送到堆栈的速度比数组慢。
这是我写的测试代码:
var Stack = require('stack-js-implementation');
var s_own = new Stack(800000);
var s_internal = new Array();
var before, after;
console.log('--- own implementation ---\n');
before = Date.now();
for (var i = 0; i < 800000; i++) {
s_own.push(i);
}
after = Date.now();
console.log('--- Add Elements to Stack Time --- : ' + (after-before) + '\n');
before = Date.now();
s_own.push(1000);
after = Date.now();
console.log('--- Push Time --- : ' + (after-before) + '\n');
console.log('\n\n');
console.log('--- internal implementation ---\n');
before = Date.now();
for (var i = 0; i < 800000; i++) {
s_internal.push(i);
}
after = Date.now();
console.log('--- Add Elements to Stack Time --- : ' + (after-before) + '\n');
before = Date.now();
s_internal.shift();
after = Date.now();
console.log('--- Shift Time --- : ' + (after-before) + '\n');
before = Date.now();
s_internal.push(1000);
after = Date.now();
console.log('--- Push Time --- : ' + (after-before) + '\n');
我运行配置文件(使用node --trace-gc test.js
)并发现问题是它导致了很多GC事件。
请帮帮我。感谢。