Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick hack / performance experiment to measure JavaScript variable byte encoding speed
// Quick hack / performance experiment to measure JavaScript variable byte encoding speed
function encodeFloat(i) {
var buf = [];
buf.push(i & 127);
i /= 128;
while(i >= 1) {
--i;
buf.push(128 + (i & 127));
i /= 128
}
return buf.reverse();
}
function decodeFloat(buf) {
var pos = 0;
var i = 0;
var b;
while(true) {
b = buf[pos++];
i = i * 128 + (b & 127);
if(b & 128) {
++i;
} else {
return i;
}
}
}
function encodeInt(i) {
var buf = [];
buf.push(i & 127);
i >>= 7;
while(i >= 1) {
--i;
buf.push(128 + (i & 127));
i >>= 7;
}
return buf.reverse();
}
function decodeInt(buf) {
var pos = 0;
var i = 0;
var b;
while(true) {
b = buf[pos++] | 0;
i = (i << 7)+ (b & 127);
if(b & 128) {
++i;
} else {
return i;
}
}
}
function encodeFloatArr(i, buf, pos0) {
var pos = pos0;
buf[pos] = i & 127;
i /= 128;
while(i >= 1) {
--i;
buf[++pos] = 128 + (i & 127);
i /= 128;
}
while(pos0 < pos) {
i = buf[pos];
buf[pos] = buf[pos0];
buf[pos0] = i;
++pos0; --pos;
}
return buf;
}
function encodeIntArr(i, buf, pos0) {
var pos = pos0;
buf[pos] = i & 127;
i >>= 7;
while(i >= 1) {
--i;
buf[++pos] = 128 + (i & 127);
i >>= 7;
}
while(pos0 < pos) {
i = buf[pos];
buf[pos] = buf[pos0];
buf[pos0] = i;
++pos0; --pos;
}
return buf;
}
/*
bench("Float arr", encodeFloat, decodeFloat);
bench("Int arr", encodeInt, decodeInt);
bench("Float arr", encodeFloatArr, decodeFloat);
*/
bench("Int arr", encodeIntArr, decodeInt);
function bench(title, enc, dec) {
var buf = new Uint8Array(30);
// find total length, and warm up jit.
var benchCount = 50000000;
var totalLength = 0;
for(var i=0;i<benchCount;++i) {
var encoded = enc(i, buf, 0);
totalLength += encoded.length;
dec(encoded, buf, 0);
if(dec(encoded, buf, 0) !== i) {
console.log("error", i, encoded, dec(encoded, buf, 0));
};
}
var t0 = Date.now();
for(i=0;i<benchCount;++i) {
dec(enc(i, buf, 0), buf, 0);
}
console.log(title, "KB/second", totalLength/1000/(Date.now() - t0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment