1

I have an array of objects

x = [{id:null},{id:null},{id:null},{id:null}];

Lets say that the values for the array changed

x = [{id:1},{id:3},{id:8},{id:12}];

And i wanted to revert the values to all null,which method will be faster for performance

A) Reconstructing the array again

 x=[];
 for (var i=0; i<5; i++) {
    var obj = {};
    obj.id = null;
    x.push(obj);
 }

B) Resetting the values

for (var i in x) {
    x.id = null;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Michael Rosales
  • 219
  • 3
  • 14

2 Answers2

0

Unless you have thousands of elements, you will never notice a difference in performances.

However the second solution is more clear than the first one.

Alternatively, to make it clear x is an array:

for (var i = 0; i < x.length; ++i) {
  x[i].id = null;
}
floribon
  • 19,175
  • 5
  • 54
  • 66
0

Your B will just add property id to your array and set it's value to 'null'. On top of that, you should not use for in on arrays.

Fastest way would probably be:

var i = x.length;
while(i--){
    x[i].id = null;
}

But you wouldn't see the difference unless your array has thousands of elements, and probably shouldn't even try to optimize it for the performance, before you're sure that you need to. In most use cases readability of the code will be much more important than a few fragments of a second that you could gain.

Community
  • 1
  • 1
Zemljoradnik
  • 2,672
  • 2
  • 18
  • 24