var genes = '-AKR1C2--AMH--AMHR2--AR--ARX--ATRX--B9D1--CBX2--CEP41--CYB5A--CYP11A1--CYP11B1--CYP17A1--CYP19A1--DHCR7--DHH--DMRT1--DYNC2H1--FRAS1--FREM2--GATA4--GRIP1--HOXA13--HSD17B3--HSD3B2--LHCGR--MAMLD1--MAP3K1--MKKS--NEK1--NR0B1--NR3C1--NR5A1--POR--RIPK4--ROR2--RSPO1--SOX3--SOX9--SRD5A2--SRY--STAR--TCTN3--TSPYL1--DYNC2I1--WNT4--WT1--ZFPM2-';
var gene = 'LHCGR';
var i = genes.indexOf('-' + gene + '-');
var i = genes.replace(/`${gene}`/i, gene);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String indexOf | |
String replace |
Test name | Executions per second |
---|---|
String indexOf | 3564042.5 Ops/sec |
String replace | 3121537.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is tested?
The provided benchmark compares two string manipulation functions in JavaScript: String.indexOf
and String.replace
. The test case uses a large string (genes
) containing many substrings, including the target substring (gene
).
Options compared:
gene
string) in the original string.gene
string (/
${gene}/i
). The replacement string is also gene
.Pros and Cons:
String.replace
, especially for small substrings.String.indexOf
due to the additional complexity of the replacement process.Library and its purpose:
In this benchmark, no external libraries are used. However, if we were to consider modern JavaScript features, String.replace
uses a technique called "regex capture groups" (/
${gene}/i
). This allows it to extract the matched substring (in this case, gene
) from the original string.
Special JS feature or syntax:
The use of template literals (e.g., "var i = genes.indexOf('-' + gene + '-');"
and "var i = genes.replace(/
${gene}/i, gene);"
) is a modern JavaScript feature. This allows for more readable and concise code by inserting the value of an expression inside a string.
Alternatives:
If you need to compare these functions with other alternatives, consider:
String.prototype.includes()
: A more modern alternative to String.indexOf
, which returns true
if the specified value is found anywhere in the original string./-+gene-+/
) for a simpler replacement process.Keep in mind that these alternatives might have different performance characteristics compared to String.indexOf
and String.replace
.