From e4b2f61fb56ce99d705735c9cc174cb47b2d8fdf Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 8 Apr 2017 02:20:40 -0400 Subject: [PATCH] buffer: use slightly faster NaN check PR-URL: https://github.com/nodejs/node/pull/12286 Reviewed-By: Timothy Gu Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- benchmark/buffers/buffer-indexof-number.js | 23 ++++++++++++++++++++++ lib/buffer.js | 6 ++++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 benchmark/buffers/buffer-indexof-number.js diff --git a/benchmark/buffers/buffer-indexof-number.js b/benchmark/buffers/buffer-indexof-number.js new file mode 100644 index 00000000000000..2e6e10b9f33d40 --- /dev/null +++ b/benchmark/buffers/buffer-indexof-number.js @@ -0,0 +1,23 @@ +'use strict'; +const common = require('../common.js'); +const fs = require('fs'); +const path = require('path'); + +const bench = common.createBenchmark(main, { + value: ['@'.charCodeAt(0)], + n: [1e7] +}); + +function main(conf) { + const n = +conf.n; + const search = +conf.value; + const aliceBuffer = fs.readFileSync( + path.resolve(__dirname, '../fixtures/alice.html') + ); + + bench.start(); + for (var i = 0; i < n; i++) { + aliceBuffer.indexOf(search, 0, undefined); + } + bench.end(n); +} diff --git a/lib/buffer.js b/lib/buffer.js index b42123824826aa..e22259dc4f1922 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -602,7 +602,8 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Coerce to Number. Values like null and [] become 0. byteOffset = +byteOffset; // If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer. - if (Number.isNaN(byteOffset)) { + // `x !== x`-style conditionals are a faster form of `isNaN(x)` + if (byteOffset !== byteOffset) { byteOffset = dir ? 0 : (buffer.length - 1); } dir = !!dir; // Cast to bool. @@ -824,7 +825,8 @@ function adjustOffset(offset, length) { // Use Math.trunc() to convert offset to an integer value that can be larger // than an Int32. Hence, don't use offset | 0 or similar techniques. offset = Math.trunc(offset); - if (offset === 0 || Number.isNaN(offset)) { + // `x !== x`-style conditionals are a faster form of `isNaN(x)` + if (offset === 0 || offset !== offset) { return 0; } else if (offset < 0) { offset += length;