<!--your preparation HTML code goes here-->
let regex = /a/
regex.test('bbbbbbbaaaaa')
'bbbbbbbaaaaa'.includes('a')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
includes |
Test name | Executions per second |
---|---|
regex | 57488392.0 Ops/sec |
includes | 209983872.0 Ops/sec |
The benchmark in question compares two different approaches for determining the presence of a character (in this case, the character 'a') within a string: using the String.prototype.includes()
method and using a regular expression (RegExp
).
Includes Method:
'bbbbbbbaaaaa'.includes('a')
true
or false
).Regular Expression:
regex.test('bbbbbbbaaaaa')
/a/
checks for the presence of the character 'a'.In this benchmark, no external libraries are directly utilized other than JavaScript's built-in capabilities. The test cases leverage the native String.prototype.includes()
method and the RegExp test method, both of which are standard features of JavaScript.
Neither test case uses special JavaScript features or syntax that deviates from standard practices. Both approaches are well-established and commonly used.
Apart from the includes
method and regular expressions, there are other ways to check for the existence of a substring, including:
Using indexOf()
:
'bbbbbbbaaaaa'.indexOf('a') !== -1
includes()
.Using Array.prototype.some()
:
[...'bbbbbbbaaaaa'].some(char => char === 'a');
includes()
or regex.In summary, the benchmark effectively compares two popular string searching techniques in JavaScript. The includes()
method is more straightforward and performs better for simple character checks, while regular expressions provide unmatched flexibility for more complex string pattern matching. Each option has its use case, and the choice between them should be guided by the specific requirements of the task at hand.