This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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