<!--your preparation HTML code goes here-->
var ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var DIGITS = '0123456789';
var ALL_CHARS = `${DIGITS}${ALPHA}`;
var CHARACTERS = ALL_CHARS.split('');
var CHARMAP = CHARACTERS.reduce((ret, char, idx) => ret.set(char, idx), new Map());
var CHAROBJ = CHARACTERS.reduce((ret, char, idx) => {ret[char] = idx; return ret;}, {});
var LETTER = 'N';
console.log('Prep:', {ALPHA,DIGITS,ALL_CHARS,CHARMAP,CHAROBJ,LETTER});
var i = ALL_CHARS.indexOf(LETTER);
var i = CHARMAP.get(LETTER);
var i = CHAROBJ[LETTER];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
Map.get | |
Object Accessor |
Test name | Executions per second |
---|---|
indexOf | 143533232.0 Ops/sec |
Map.get | 151962352.0 Ops/sec |
Object Accessor | 69664960.0 Ops/sec |
The benchmark you provided compares three different methods for finding the index of a character within a predefined set of characters:
String.indexOf
LETTER
(which is 'N'
) in a string of all characters, ALL_CHARS
.-1
if the character is not found, which might require additional handling.Map.get
Map
, which is a collection of keyed data items.Map
named CHARMAP
is created where each character maps to its corresponding index, allowing for efficient lookups.undefined
naturally.Map
structure.Object Accessor
CHAROBJ
) to get the value associated with the LETTER
key.Map
, it stores the index of each character as object properties.Map
.The benchmark results indicate the performance of each method in terms of ExecutionsPerSecond
:
From the results, Map.get
is the fastest method, likely due to its O(1) lookup characteristic, followed closely by String.indexOf
, and then Object Accessor
which performs the slowest in this scenario.
Choosing the Right Method: When performance is a critical consideration (especially in cases of frequent character lookups), using a Map
would be preferable. For simpler cases or where memory overhead matters less, String.indexOf
or the Object Accessor
might suffice, especially given their widespread familiarity among developers.
Alternatives:
Ultimately, the choice between these options will depend on the specific needs for performance, readability, and memory management in a user's application context.