Skip to content

Instantly share code, notes, and snippets.

@wesgarland
Created March 1, 2022 23:12
Show Gist options
  • Save wesgarland/06cb328984e38a1450618194b3d03983 to your computer and use it in GitHub Desktop.
Save wesgarland/06cb328984e38a1450618194b3d03983 to your computer and use it in GitHub Desktop.
node-mysql2 parseFloat benchmarking
#! /usr/bin/env node
'use strict';
const minus = '-'.charCodeAt(0);
const plus = '+'.charCodeAt(0);
// TODO: handle E notation
const dot = '.'.charCodeAt(0);
const exponent = 'e'.charCodeAt(0);
const exponentCapital = 'E'.charCodeAt(0);
function parseFloatOld(len) {
if (len === null) {
return null;
}
let result = 0;
const end = this.offset + len;
let factor = 1;
let pastDot = false;
let charCode = 0;
if (len === 0) {
return 0; // TODO: assert? exception?
}
if (this.buffer[this.offset] === minus) {
this.offset++;
factor = -1;
}
if (this.buffer[this.offset] === plus) {
this.offset++; // just ignore
}
while (this.offset < end) {
charCode = this.buffer[this.offset];
if (charCode === dot) {
pastDot = true;
this.offset++;
} else if (charCode === exponent || charCode === exponentCapital) {
this.offset++;
const exponentValue = parseInt(end - this.offset);
return (result / factor) * Math.pow(10, exponentValue);
} else {
result *= 10;
result += this.buffer[this.offset] - 48;
this.offset++;
if (pastDot) {
factor = factor * 10;
}
}
}
return result / factor;
}
const _parseFloat = global.parseFloat;
function parseFloatNew(len)
{
const ret = _parseFloat(this.buffer.slice(this.offset, this.offset + len).toString('ascii'));
this.offset += len;
return ret;
}
function Float()
{
this.offset = 0;
this.buffer = Buffer.from([ 48, 46, 52, 53, 52, 57, 52, 50, 53, 51, 56, 52, 51, 49, 49, 57, 48, 48, 52 ]);
}
Float.prototype.parseFloatOld = parseFloatOld;
Float.prototype.parseFloatNew = parseFloatNew;
const num = new Float();
console.log(Array.from(num.buffer.map((c) => String.fromCharCode(c))));
num.offset = 0;
const a = num.parseFloatOld(19)
console.log(a);
num.offset = 0;
const b = num.parseFloatNew(19);
console.log(b);
measure('old', () => { num.offset = 0; void num.parseFloatOld(19); });
measure('new', () => { num.offset = 0; void num.parseFloatNew(19); });
function measure(label, fun, howMany = 1000000)
{
fun();
fun();
fun();
const start = Date.now();
for (let i=0; i < howMany; i++)
fun();
const end = Date.now();
console.log(label, ':', (end-start) + 'ms');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment