const regexp = new RegExp(/^\-\-/);
const prefix = "--";
const str = "--some-var";
const numTests = 10000;
let i = 0;
while (i < numTests) {
str.startsWith(prefix);
i++;
}
let i = 0;
while (i < numTests) {
regexp.test(str);
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.startsWith() | |
RegExp |
Test name | Executions per second |
---|---|
.startsWith() | 11413.1 Ops/sec |
RegExp | 159610.1 Ops/sec |
The benchmark provided tests two different methods for determining whether a string starts with a specific prefix: using the .startsWith()
method and leveraging a regular expression (RegExp).
.startsWith()
Method
.startsWith()
method is a built-in JavaScript method that checks if a given string begins with a specified sequence of characters, returning a boolean value (true
or false
).numTests
(10,000) times, calling str.startsWith(prefix)
each time, where str
is the string being tested and prefix
is the substring to check against..startsWith()
is generally faster and more optimized in most JavaScript engines.Regular Expression (RegExp)
regexp.test(str)
in the same loop for numTests
..startsWith()
due to the added overhead of pattern matching.The benchmark results show the following performance:
From the results, we can observe that regular expressions are significantly faster for this specific test case with short strings and prefixes. This can be surprising, as one might expect that the simpler method, .startsWith()
, would be quicker due to its straightforward purpose.
.startsWith()
is preferred due to its clarity and intended usage. However, if there’s a need for more complex validation where patterns are involved, then RegExp becomes the necessary choice, despite its complexity and potentially lower readability.str.indexOf(prefix) === 0
to check if a string starts with a given prefix. This method is less readable than .startsWith()
and may be less efficient in terms of performance.str.slice(0, prefix.length) === prefix
). While this can work, it also reduces readability and may have performance implications similar to indexOf
.The choice between .startsWith()
and RegExp encapsulates a balance between readability, performance, and complexity. It’s essential for developers to consider the specific use case and context when selecting the method for performance string checks. Regular expressions, while powerful, should be reserved for cases where their capabilities are needed, rather than for simple checks, where .startsWith()
is usually sufficient and clearer.