Optimize Javascript Code On Searching For Matches In Array
Solution 1:
I compared three possible implementations:
Alternative 1 - Using for loop:
functionalternative1(aValidWords, sMainWordLower) {
var aPossibleWords1 = [];
for(i=0; i < aValidWords.length; i++){
if(sMainWordLower.indexOf(aValidWords[i]) != -1){
aPossibleWords1.push(aValidWords[i]);
}
}
return aPossibleWords1;
}
Alternative 2 - Using jQuery grep function:
functionalternative2(aValidWords, sMainWordLower) {
return $.grep(aValidWords, function(word) {
return sMainWordLower.indexOf(word) != -1;
}
)
}
Alternative 3 - Using JavaScript native filter method (IE9, Chrome, Firefox, Opera, Safari):
functionalternative3(aValidWords, sMainWordLower) {
return aValidWords.filter(function(word) {
return sMainWordLower.indexOf(word) != -1;
}
)
}
I measured the execution times with Chrome Profile tool. Each alternative was executed 10 times with array of random milion words. The results are:
- Alternative 1: 20 executions -> 21,68s
- Alternative 2: 20 executions -> 26,31s
- Alternative 3: 20 executions -> 34,66s
I was surprised by the fact, that native JavaScript Filter function was so slow.
If you wan't to measure execution times by yourself, there is jsFiddle - it will take some time for script to finish.
In general those three alternatives are easiest. If those execution times suits you, use one of them, otherwise the answer of @Pumbaa80 is the right one.
[UPDATE]
For the explanation of the results (why JQuery grep funcion is faster then native JavaScript filter function) please take a look at this question/answer. jsFiddle code was also ported to jsPerf thanks to @Alexander.
Solution 2:
I think your code is decent.
If you're really worried about performance, you may want to try some sophisticated method like Boyer-Moore. But, if you just have a handful of patterns and relatively short strings, then the initialization overhead is higher than the benefit, so you should stick with the simple approach. See Wikipedia's comparison table http://en.wikipedia.org/wiki/String_searching_algorithm#Single_pattern_algorithms
Solution 3:
This loop is definitely more concise than what you have, but it'd be worth running some tests in various browsers to find out which is faster. I imagine Regex matching is probably faster, but I'm curious whether there's any performance penalty for compiling the Regex.
for(var i=0; i<aValidWords.length; i++) {
if (new RegExp(aValidWords[i], 'i').test(sMainWord))
aPossibleWords.push(aValidWords[i]);
}
Post a Comment for "Optimize Javascript Code On Searching For Matches In Array"