Skip to content

Commit

Permalink
buffer: use slightly faster NaN check
Browse files Browse the repository at this point in the history
PR-URL: #12286
Reviewed-By: Timothy Gu <timothygu99@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
  • Loading branch information
mscdex authored and evanlucas committed Apr 25, 2017
1 parent 762bd5d commit ab963c1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
23 changes: 23 additions & 0 deletions benchmark/buffers/buffer-indexof-number.js
Original file line number Diff line number Diff line change
@@ -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);
}
6 changes: 4 additions & 2 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit ab963c1

Please sign in to comment.