Skip to content

Commit

Permalink
The iterator for arguments sucks - refactor to avoid calling it
Browse files Browse the repository at this point in the history
The `arguments` iterator is extremely slow, and as such adds a
significant amount of overhead when called in the middle of a hot loop.
Manually iterating instead results in a large performance gain, and
avoiding the arguments object entirely for the first value gains a
little more.
  • Loading branch information
erayd committed Sep 29, 2016
1 parent e852aee commit 83c9f94
Showing 1 changed file with 34 additions and 26 deletions.
60 changes: 34 additions & 26 deletions spique.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,38 +45,46 @@ function Spique(maxItems, ringSize) {
};

// push item(s) onto the end of the buffer
this.enqueue = this.push = function() {
for(var value of arguments) {
if(items >= maxItems)
this.enqueue = this.push = function push(value) {
if(items >= maxItems)
return new Error('Buffer is full');
// add another ring if necessary
if(!lastRing.available()) {
var newRing = allocateRing();
lastRing.nextRing = newRing;
newRing.prevRing = lastRing;
lastRing = newRing;
rings++;
}
lastRing.push(value);
items++;

// process variadic args
for(var argIndex = 1; argIndex < arguments.length; argIndex++) {
if(push(arguments[argIndex]))
return new Error('Buffer is full');
// add another ring if necessary
if(!lastRing.available()) {
var newRing = allocateRing();
lastRing.nextRing = newRing;
newRing.prevRing = lastRing;
lastRing = newRing;
rings++;
}
lastRing.push(value);
items++;
}
}

// push item(s) onto the start of the buffer
this.unshift = function(value) {
for(var value of arguments) {
if(items >= maxItems)
this.unshift = function unshift(value) {
if(items >= maxItems)
return new Error('Buffer is full');
// add another ring if necessary
if(!firstRing.available()) {
var newRing = allocateRing();
newRing.nextRing = firstRing;
firstRing.prevRing = newRing;
firstRing = newRing;
rings++;
}
firstRing.unshift(value);
items++;

// process variadic args
for(var argIndex = 1; argIndex < arguments.length; argIndex++) {
if(unshift(arguments[argIndex]))
return new Error('Buffer is full');
// add another ring if necessary
if(!firstRing.available()) {
var newRing = allocateRing();
newRing.nextRing = firstRing;
firstRing.prevRing = newRing;
firstRing = newRing;
rings++;
}
firstRing.unshift(value);
items++;
}
}

Expand Down

0 comments on commit 83c9f94

Please sign in to comment.