Created
June 2, 2024 17:54
-
-
Save fabiospampinato/fd80d9b6a25eb4504b8a8eb945670157 to your computer and use it in GitHub Desktop.
String.prototype.indexOf vs Uint8Array.prototype.indexOf
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 string = ` ${'This is just some example big file with lots of strings\n'.repeat ( 100_000 )}`.slice ( 1 ); | |
const uint8 = new TextEncoder ().encode ( string ); | |
const getRangesFromString = value => { | |
let pos = 0; | |
let length = value.length; | |
while ( pos < length ) { | |
const startIndex = value.indexOf ( '\n', pos ); | |
if ( startIndex === -1 ) break; | |
pos = startIndex + 1; | |
} | |
}; | |
const getRangesFromUint8 = value => { | |
let pos = 0; | |
let length = value.length; | |
while ( pos < length ) { | |
const startIndex = value.indexOf ( 10, pos ); // \n | |
if ( startIndex === -1 ) break; | |
pos = startIndex + 1; | |
} | |
}; | |
console.log ( 'string length', string.length ); | |
console.log ( 'uint8 length', uint8.length ); | |
console.time ( 'uint8' ); | |
for ( let i = 0; i < 500; i++ ) { | |
getRangesFromUint8 ( uint8 ); | |
} | |
console.timeEnd ( 'uint8' ); | |
console.time ( 'string' ); | |
for ( let i = 0; i < 500; i++ ) { | |
getRangesFromString ( string ); | |
} | |
console.timeEnd ( 'string' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment