Reputation: 1616
I have a question about map.As you know by using map we can iterate arrays and able to change the element of arrays.To do that there are two ways and I listed them below.Which way has less complexity and more performance?(In the examples arrays are not big but think about the real world like 500 elements in an array)
var numbers = [4, 9, 16, 25];
numbers=numbers.map(e=>{
return e=e*2;
})
In this approach assigning each returned value to current array.
numbers.map((e,a)=>{
numbers[a]=e*2;
})
In this one on each iteration we need to go to array by index to find element and I think this is worse than above but Im not sure.
Upvotes: 1
Views: 2142
Reputation: 177975
Semantically you need for
or forEach
when you do not need a new array.
For sufficiently small arrays there is no difference in performance
var numbers = [4, 9, 16, 25];
numbers.forEach((e,i)=> numbers[i] = e*2);
console.log(numbers)
Upvotes: 2
Reputation: 386620
The fastest way to change a value of an array is to iterate the index and update the item.
This approach is faset than forEach
or map
, because it does not have the overhead of this
and it does not need the feature of the supplied structure of the callback.
var numbers = [4, 9, 16, 25];
for (let i = 0; i < numbers.length; i++) numbers[i] *= 2;
console.log(numbers);
Upvotes: 0
Reputation: 35512
nums.forEach((v, i) => nums[i] = v);
is the fastest method possible that you listed (equivalent to your second method. Why? nums = nums.map(...)
creates an entire copy of the array in memory and replaces the array with that copy. When you simply iterate over the array with an index and replace elements, you avoid making that copy, and it ends up being around 15% faster (see this benchmark.
Upvotes: 1
Reputation: 1074395
Don't use map
if you're not going to use the array it creates. If you just want to loop through an array, use a loop or forEach
or similar.
Whether you want a new array or not, the most efficient way to loop through an array is usually a for
loop:
const numbers = [4, 9, 16, 25];
for (let i = 0, len = numbers.length; i < len; ++i) {
numbers[i] = numbers[i] * 2;
}
(Or any of several variations on that.)
But "most efficient" is extremely unlikely to actually matter in real-world code, so using things like map
(if you want a new array) or forEach
(if you don't) is just fine. map
is idiomatic for that operation (creating a new array containing the entries from a previous array modified in some way).
Conclusion:
If you want a new array, feel free to use map
, or create a blank array and use any of your options for looping arrays to loop the original and add entries to the new one.
If you don't want a new array, don't use map
, use any of your options for iterating over the original except for ones that don't give you the index, and assign the updated value back to the entry.
Upvotes: 5