Skip to content

Instantly share code, notes, and snippets.

@sidorares
Created March 2, 2022 01:07
Show Gist options
  • Save sidorares/9ddbcd31e175b7534021712e94b93800 to your computer and use it in GitHub Desktop.
Save sidorares/9ddbcd31e175b7534021712e94b93800 to your computer and use it in GitHub Desktop.
const { performance } = require("perf_hooks");
const minus = "-".charCodeAt(0);
const plus = "+".charCodeAt(0);
const dot = ".".charCodeAt(0);
const exponent = "e".charCodeAt(0);
const exponentCapital = "E".charCodeAt(0);
function bufToFloat(buf, start, len) {
let offset = start;
let result = 0;
const end = offset + len;
let factor = 1;
let pastDot = false;
let charCode = 0;
if (buf[offset] === minus) {
offset++;
factor = -1;
}
if (buf[offset] === plus) {
offset++; // just ignore
}
while (offset < end) {
charCode = buf[offset];
if (charCode === dot) {
pastDot = true;
offset++;
} else if (charCode === exponent || charCode === exponentCapital) {
offset++;
const exponentValue = this.parseInt(end - this.offset);
return (result / factor) * Math.pow(10, exponentValue);
} else {
result *= 10;
result += buf[offset] - 48;
offset++;
if (pastDot) {
factor = factor * 10;
}
}
}
return result / factor;
}
function pad(str) {
if (str.length > 10) {
return str.slice(0, 10);
}
const zeroes = "0000000000";
return str + zeroes.slice(0, 10 - str.length);
}
const buf = Buffer.alloc(10000000 * 10);
for (let offset = 0; offset < buf.length; offset += 10) {
const str = pad(Math.random().toString(10));
buf.write(str, offset);
}
function benchmark() {
let acc = 0;
const start = performance.now();
for (let offset = 0; offset < buf.length; offset += 10) {
const str = buf.toString("ascii", offset, offset + 10);
const number = parseFloat(str, 10);
acc += number;
}
const duration = performance.now() - start;
console.log(`parsing done (global.parseFloat), resul: ${acc} in ${duration} ms`);
}
function benchmark2() {
let acc = 0;
const start = performance.now();
for (let offset = 0; offset < buf.length; offset += 10) {
const number = bufToFloat(buf, offset, 10);
acc += number;
}
const duration = performance.now() - start;
console.log(`parsing done, resul: ${acc} in ${duration} ms`);
}
for (let i=0; i < 10; ++i) {
benchmark();
}
for (let i=0; i < 10; ++i) {
benchmark2();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment