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;