Skip to content

Instantly share code, notes, and snippets.

@jsalonen jsalonen/outrun.js
Last active Aug 29, 2015

Embed
What would you like to do?
Out Run - Performance Optimized Implementation with JavaScript on node.js
'use strict';
var fs = require('fs'),
instream = fs.createReadStream(process.argv[2]),
bufferSize = 16384,
buffer1 = new Int32Array(bufferSize),
buffer2 = new Int32Array(bufferSize),
seedReader = true,
_a = 0,
_token = -1,
_tokens = 1;
function Int32Concat (first, second) {
var firstLength = first.length,
result = new Int32Array(firstLength + second.length);
result.set(first);
result.set(second, firstLength);
return result;
}
instream.on('readable', function(inData) {
var inData = instream.read(),
inDataLength = inData.length,
i = 0,
a = _a,
b = 0,
token = _token,
tokens = _tokens;
if(seedReader) {
while(inData[i] != 10) {
i++;
}
seedReader = false;
}
while(i<inDataLength) {
var charCode = inData[i];
if(charCode>=48 && charCode<=57) {
if(token<0) {
token++;
}
token = token*10 + (charCode-48);
} else {
if(token>=0) {
b = buffer2[tokens];
buffer1[tokens] = token + a-((a-b)&(a-b)>>31);
tokens++;
a = b;
}
if(charCode==10) {
var tmp = buffer2; buffer2 = buffer1; buffer1 = tmp;
if(tokens>=bufferSize-1) {
buffer1 = Int32Concat(buffer1, new Int32Array(bufferSize));
buffer2 = Int32Concat(buffer2, new Int32Array(bufferSize));
bufferSize *= 2;
}
tokens = 1;
a = 0;
}
token = -1;
}
i++;
}
_a = a;
_token = token;
_tokens = tokens;
});
instream.on('end', function() {
console.log(Math.max(
Math.max.apply(Math, buffer1),
Math.max.apply(Math, buffer2)
));
});
$ time node outrun.js outrun.txt
743182
real 0m0.858s
user 0m0.015s
sys 0m0.015s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.