var str = 'https://www.testsite.com/some-path/another-path/2019/my-amazing-page-name.html';
str.replace(/^(.*[\\\/])/, '');
str.replace(/([^\/]+)(?=[^\/]*\/?$)/, '');
str.split('/').pop();
str.substring(str.lastIndexOf('/')+1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Regex 1 | |
Regex 2 | |
Split | |
Substring |
Test name | Executions per second |
---|---|
Regex 1 | 6696437.0 Ops/sec |
Regex 2 | 268581.3 Ops/sec |
Split | 6366050.5 Ops/sec |
Substring | 36807152.0 Ops/sec |
Benchmark Overview
The provided benchmark tests the performance of three different approaches to extract the last part from a URL: using regular expressions (Regex 1
and Regex 2
), splitting by /
(Split
), and using the substring()
method with lastIndexOf()
. The benchmark aims to determine which approach is the fastest on the specified hardware configuration.
Benchmark Definitions
The three test cases are:
Regex 1
: Uses a regular expression to remove everything before the first /
, leaving only the last part of the URL. The pattern used is ^(.*[\\\\\\/])
, which matches any characters (.
) followed by either a backslash or a forward slash (\\
or /
). The parentheses create a capture group, allowing us to extract the matched text.Regex 2
: Similar to Regex 1
, but with an additional positive lookahead assertion ((?=[^\\/]*\\/?$)
) to ensure that the extracted string does not contain any more forward slashes. This is done by checking if there are no more non-slash characters before or after the last forward slash.Split
: Splits the URL into substrings using /
as the separator and returns the last part of the array using pop()
.Substring
: Uses lastIndexOf()
to find the position of the last occurrence of /
in the URL and then extracts a substring starting from that index, effectively getting the last part.Approach Comparison
Regular Expressions (Regex):
Regex 2
has a slight performance advantage over Regex 1
likely because of the additional lookahead assertion which makes it less ambiguous for the engine.Library Used: JavaScript's built-in String.prototype.replace()
method uses regular expressions under the hood.
Split:
Substring:
Regex
due to fewer overheads.lastIndexOf()
) to find the last occurrence of /
, which can add to overall execution time.Special Features
None mentioned in this explanation.