var str = 'fred red bed said', searchTerm = 'bed',
arr = str.split(' ');
function removeSubstr(str, substr){
tmp = " " + str + " ";
substr = " " + substr + " ";
if (tmp.indexOf(substr) !== -1 ) {
tmp = tmp.replace(substr, "").trim();
return tmp
}
return str;
}
function removeSubstr2(str, substr){
var len = str.length, tmp = (" " + str + " ").replace(" " + substr + " ", "").trim();
if ( str.length < len ) return tmp;
return str;
}
function removeSubstr3(str, substr){
var strSpl = str.split(' '), idx = strSpl.indexOf(substr);
if ( idx > -1) {
return strSpl.splice(idx, 1).join(' ');
}
return str;
}
function removeElem(arr, substr){
var idx = arr.indexOf(substr);
if ( idx > -1) {
return arr.splice(idx, 1);
}
return arr;
}
removeSubstr(str, searchTerm)
removeSubstr2(str, searchTerm)
removeSubstr3(str, searchTerm)
removeElem(arr, searchTerm)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String Replace No Compare | |
String Replace With Compare | |
Convert to Array | |
Remove From Array |
Test name | Executions per second |
---|---|
String Replace No Compare | 179087.3 Ops/sec |
String Replace With Compare | 238998.1 Ops/sec |
Convert to Array | 124368.9 Ops/sec |
Remove From Array | 903509.2 Ops/sec |
I'd be happy to help you understand what's being tested on the provided JSON benchmark.
The benchmark is testing four different approaches for removing a specific substring from either a string or an array:
replace()
method to remove the substring from the original string.indexOf()
, and only then performs the replacement.split()
, and then uses the indexOf()
method to find and remove the substring from the array.indexOf()
method to find the index of the substring in the input array, and then uses splice()
to remove it from the array.The benchmark is comparing the execution times of these four approaches for different test cases. The results show that:
It's worth noting that these results are specific to Chrome 52 on Windows and may not reflect performance differences on other browsers or platforms.