<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
/*When writing async/deferred tests, use `deferred.resolve()` to mark test as done*/
const hasSubdomain = (hostname) => {
return hostname.split('.').length > 2;
};
hasSubdomain('pixel.barion.com');
const hasSubdomain = (hostname) => {
return /^[^.]+\.[^.]+\./.test(hostname);
};
hasSubdomain('pixel.barion.com');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Split | |
RegExp |
Test name | Executions per second |
---|---|
Split | 12315885.0 Ops/sec |
RegExp | 15790837.0 Ops/sec |
The benchmark defined on MeasureThat.net compares two approaches to determine if a given hostname contains a subdomain: using a string split
method versus using a regular expression (RegExp). Below is a detailed examination of each option, their pros and cons, and some other considerations relevant for software engineers.
Split Method
const hasSubdomain = (hostname) => {
return hostname.split('.').length > 2;
};
.
(dot) character and checks if the resultant array has more than two elements. If true, the function indicates the presence of a subdomain.Regular Expression (RegExp)
const hasSubdomain = (hostname) => {
return /^[^.]+\\.[^.]+\\./.test(hostname);
};
Pros:
Cons:
split
creates an array in memory which can be slightly more resource-intensive, especially with longer hostnames.Pros:
Cons:
Performance Metrics: Both methods demonstrated high performance, with the split method marginally outpacing the RegExp in this benchmark. Consider real-world scenarios for critical applications where performance differences might scale or vary based on usage patterns.
Alternatives: Other ways to implement subdomain checks include:
URL
constructor in JavaScript can be used, enabling structured parsing of URL components.indexOf
to find the position of the first .
) could be a potential alternative, providing both flexibility and a mapped performance model.Usability: The choice between these methods often depends on the specific requirements of the project, including the anticipated size of the input data, performance needs, and code maintainability.
In conclusion, while both methods are viable for detecting subdomains, the trade-offs between performance, readability, and complexity dictate which approach may be the most appropriate for different applications or environments.