Reputation: 3
I am creating a function that will accept two parameters, which are each arrays, and return a separate array of matching values between the two arrays.
I made two versions of the function,
for
loop, and checks the second parameter for a matching value using .includes()
ex:
var matches = [];
for (let i = 0, len = array1.length; i < len; i++) {
var a = array1[i];
if (array2.includes(a)) {
matches.push(a)
}
for
loopex:
if (array1.length <= array2.length) {
var itArr = array1;
var checkArr = array2 }
else { var itArr = array2
var checkArr = array1 };
var matches = [];
for (let i = 0, len = itArr.length; i < len; i++) {
var a = itArr[i];
if (checkArr.includes(a)) {
matches.push(a)
}
My question is whether or not this actually improves the performance, or makes no difference, or harms the performance (by adding more variable definitions, calculations, etc.)?
Upvotes: 0
Views: 269
Reputation: 24181
Here is an example of using a Set for seeing if one array contains values from the other.
If your not ES6, (and why not?), you could use a simple object literal.
This should be faster than doing a double for loop, as that's kind of what includes would be doing.
function makeRandom(count, max) {
return Array.from(new Array(count),
(a,ix) => Math.round(Math.random() * max));
}
function union(a,b) {
var aSet = new Set(a), oSet = new Set();
b.forEach((v) => { if(aSet.has(v)) oSet.add(v) });
return Array.from(oSet);
}
const
random1 = makeRandom(5, 10),
random2 = makeRandom(5, 10);
const
unionArray = union(random1, random2);
console.log(random1.join(':'));
console.log(random2.join(':'));
console.log(unionArray.join(':'));
Upvotes: 0
Reputation: 122
I think I would go for the first approach, due to the .includes function will try to iterate the array and return true when it finds the element, so if the element is in the end of the array it iterates completely on it. Hence your attempt for chosing the small one shouldn't make too much difference.
Upvotes: 0
Reputation: 10458
It wouldn't make significant difference since the worst case complexity would be O(n*m) where n and m are the length of the arrays.
You can sort the 2 arrays and find the intersection using 2 pointers, The time complexity in that case would be O(nlogn + mlogm + n + m) subject to the sorting algorithm used
Upvotes: 1