Skip to content

Commit e4b2f61

Browse files
mscdexevanlucas
authored andcommitted
buffer: use slightly faster NaN check
PR-URL: #12286 Reviewed-By: Timothy Gu <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent 6a45be2 commit e4b2f61

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'use strict';
2+
constcommon=require('../common.js');
3+
constfs=require('fs');
4+
constpath=require('path');
5+
6+
constbench=common.createBenchmark(main,{
7+
value: ['@'.charCodeAt(0)],
8+
n: [1e7]
9+
});
10+
11+
functionmain(conf){
12+
constn=+conf.n;
13+
constsearch=+conf.value;
14+
constaliceBuffer=fs.readFileSync(
15+
path.resolve(__dirname,'../fixtures/alice.html')
16+
);
17+
18+
bench.start();
19+
for(vari=0;i<n;i++){
20+
aliceBuffer.indexOf(search,0,undefined);
21+
}
22+
bench.end(n);
23+
}

‎lib/buffer.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,8 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir){
602602
// Coerce to Number. Values like null and [] become 0.
603603
byteOffset=+byteOffset;
604604
// If the offset is undefined, "foo",{}, coerces to NaN, search whole buffer.
605-
if(Number.isNaN(byteOffset)){
605+
// `x !== x`-style conditionals are a faster form of `isNaN(x)`
606+
if(byteOffset!==byteOffset){
606607
byteOffset=dir ? 0 : (buffer.length-1);
607608
}
608609
dir=!!dir;// Cast to bool.
@@ -824,7 +825,8 @@ function adjustOffset(offset, length){
824825
// Use Math.trunc() to convert offset to an integer value that can be larger
825826
// than an Int32. Hence, don't use offset | 0 or similar techniques.
826827
offset=Math.trunc(offset);
827-
if(offset===0||Number.isNaN(offset)){
828+
// `x !== x`-style conditionals are a faster form of `isNaN(x)`
829+
if(offset===0||offset!==offset){
828830
return0;
829831
}elseif(offset<0){
830832
offset+=length;

0 commit comments

Comments
(0)