What is the difference between the two structures of the arrays and their repeating links in Javascript? [closed]

5

I would like to know which one is most suitable for working with arrays?

var meu_array = new Array(1, 2, 3);
var meu_array = [1, 2, 3];

Is there any performance difference between the 6 cases presented in the use of loop below?

 // foreach 
    meu_array.forEach(function(valor, i){
        console.log(valor, i);
    }); 
 // for key associativa
    for (var i in meu_array) {
        console.log(meu_array[i], i);
    }
 // for valor associativo  
   var i = 0;
   for (value of meu_array) {
       console.log(value, i++);
   }
 // for interator
    for (var i=0; i<=meu_array.length; i++) {
        console.log(meu_array[i], i);
    }
 // while
    var i=0;
    while (i <= meu_array.length) {
          console.log(meu_array[i], i);
     i++;
    }
 // jquery
    $.each(meu_array, function(i, value) {
      console.log(value, i);
    });
    
asked by anonymous 17.09.2015 / 21:55

1 answer

4
Essentially it makes no practical difference. They create the same array and the performance will be the same for it. The performance may be a bit better for the first case, but only at creation and there will be very little difference to care about. And this depends on language implementation. Do not count on this.

There is a difference in performance for the algorithm used in each exemplified situation, but not because the array was created one way or another.

The first form is considered confusing because if you want to create an array with only one element, it will not do what you expect. It will create an array with the specified number of elements and not an array with an element of that value.

In addition it will call the constructor that will construct the array . The second form will create the array without going through the constructor. This may seem to give the same. But there is no guarantee in language that this is true. You can override the method.

The general recommendation is not to use Array() unless you really need it and know what you're doing and why you're preferring it.

    
17.09.2015 / 22:03