I am solving some exercises and comparing my results with others. I found two very similar lines that solve the problem but I would like to know which of them is better optimized.
These are the lines:
return a1.filter(a => a2.some(b => b.includes(a))).sort();
return a1.filter(x=> a2.join(' ').includes(x)).sort()
Both lines solve the problem, but how to know which of the two is more efficient?
+INFO
In general, what the code does is take two arrays. The array a1
must return only words that are substrings of any member ofa2
Doing a quick test in JSPerf , the second algorithm is 50% slower than the first:
But maybe it's because of the examples I've used as a sample (something simple to be honest and it's also neat):
What the two algorithms do:
some()
will return true as soon as the function passed as callback returns true . This means that you don't have to go through all the elements of the array in each pass to execute theincludes()
. As soon as it finds 1, it's over.a1
, do a join of the arraya2
(with join() ) and check if the element exists in the resulting string withincludes()
.Ignoring the
sort
, which would be the same, it would make sense that the first algorithm would be (considerably) faster because it performs fewer operations and less expensive operations:Based on this, and for further testing, what you could do is move the chain creation outside the filter. That way it will only run once (you don't need it to run any more) and you'll save numerous operations:
I have added that example to JSPerf and it is the one that obtains the best results of the three (although it is necessary to consider that the strings are ordered):
Theoretical explanation:
a2
(of size N) once for each element ofa1
(of size N), resulting in N * N = N 2 .a2
(of size N) is traversed integer each time the string needs to be generated (ignoring that it is a more expensive operation) and that happens once for each element ofa1
(of size N), resulting in N * N = N 2 .a1
is traversed only once (N) and thena2
traversed once (N) comparing each element to the string, leaving N + N = 2N ~ N.Why is the first algorithm then so much faster than the second even when they have the same order of complexity? For two reasons:
some
in this case; Y