Using the new Array (n) JavaScript declaration

The main JavaScript question: since there is no hard limit for arrays, as is the case with Java (i.e., IndexOutOfBoundsException ), what is the use of a declaration in which we specify the length property?

var a = new Array(10); 

I know that it predetermines the length and puts "undefined" in these empty spaces. Is this enough for this?

+48
javascript
Aug 07 '09 at 18:51
source share
9 answers

There are many perceived benefits of declaring an array size, but I think most of the perceived benefits are just FUDs that are passed.

Better performance! / It's faster!

As far as I can tell, the difference between pre-allocation and dynamic allocation is not significant.

More interestingly, the specification does not state that the array must be set to a pre-allocated length!

From section 15.4.2.2 of ECMA-262 :

If the argument len ​​is Number and ToUint32 (len) is equal to len, then the length property for the newly created object is set to ToUint32 (len). If the argument len ​​is Number and ToUint32 (len) is not equal to len, a RangeError exception is thrown .

Unscientific script for fun: http://jsbin.com/izini

This makes the code clearer!

Personally, I do not agree.

Consider the javascript you wrote in the past, and consider the code you might have to write in the future. I can not think of a single case when I needed to specify a static limit for one of my arrays. I also argue that the potential problems with array constraints in javascript far outweigh the benefits of having people know what you were thinking about without any actual checks. Allows you to weigh the pros and cons ...

Pros:

  • It will be easier for them to understand what exactly you should do.
  • Now they will be able to find errors caused by your assumption (tongue on the cheek)

Minuses:

  • A quick glance can easily confuse the "new array (10)" with the "new array (" 10 "), which does completely different things!
  • You enter an arbitrary limit for the code without a normal length limit, forcing you to write a lot of boiler plate code to check and maintain the limit.
  • You impose an arbitrary limit on the code, which, perhaps, would be generalized to work with any length of values.
  • You make assumptions about how people will read your code, assuming that the alternative will be less confusing.

You can also write:

 //I assume this array will always be length 10 var arr = new Array(); 

In the above case, commenting might even be preferable. An explicit declaration of intent can avoid confusion that is not used to use the constructor as a declaration of intent.

Ok, then .. why do you think it's even there?

Convenience. When they wrote the specification, I think they understood two things.

  • Such an assignment will be that developers coming from similar languages ​​will be used.
  • ECMAScript implementations can potentially use it to improve performance.

So they put it there. The specification defines the use of the parameter, and not how to implement it.

+40
Aug 07 '09 at 21:05
source share

Performance on the JavaScript V8 engine.

Performing:

 var arr = []; arr.length = 1000; 

V8 predetermines the required memory for the array and supports / installs the Hidden Class array in a compact SMI array (Small Int, 31 bits unsigned). However, this is not true when the desired length is too long, which leads to the fact that HC is installed in a sparse array (i.e. Map).

Try using the following link in Chrome: http://jsperf.com/0-fill-n-size-array

I included an additional test case without determining the length of the array so that you can find out the actual difference in performance.

Additional Information: http://www.youtube.com/watch?v=UJPdhx5zTaw

+26
Jul 03 '12 at 17:59
source share

Clarity.

When writing code, your goal is not so much that the computer can understand you, but for the next programmer who reads your code to understand you.

 var xs = new Array(10); 

The code above shows your intention : to have an array of 10 elements.

 var xs = []; 

The above gives nothing; no further information.

Greetings.

+7
Aug 07 '09 at 18:57
source share

I'm not sure, but I would argue that it allocates memory differently at a low level. If you know that you are creating 10,000 items, just reserve a lot of space instead of dynamically changing it in the background all the time.

+6
Aug 07 '09 at 18:53
source share

I created this JSPerf that demonstrates the problem, including its various versions. The arguments I find are as follows:

  • Using a new array () may behave unexpectedly, may be overridden
  • The .length parameter does not actually increase the size of the array in some browsers.
  • The performance hit is actually not there.

I think that these tests should put these arguments in order, but it should be noted that different browsers treat this problem in a completely different way. Firefox seems to be optimizing and figuring out how large the array is, and Chrome allocates memory, as you would expect. And, as usual, Internet Explorer just stinks of this task.

+2
Aug 07 '15 at 3:36
source share

Suppose you want an array of a specific length to be initialized with a specific value. This will not work:

 scores = [].fill(0.0, 0, studentCount); 

It will just give you an empty array, because fill () will never expand the array beyond its original length.

This will work:

 scores = new Array(studentCount).fill(0.0, 0, studentCount); 

It will give you an array of studentCount values ​​initialized to zero.

+2
Dec 06 '17 at 19:41
source share

It is not difficult to save the size of the array. Take a look at the following example:

 function updateArray(){ var a = [1,2,3,4,5,6,7,8,9,10]; //original array object var b = [11, 12, 13]; //New array object to be pushed a.splice(a.length-b.length, a.length); a.unshift.apply(a, b); return a; } 

a.unshift.apply(arg1, arg2) click on the new item at the top and a.push.apply(arg1, arg2) at the bottom.

0
Nov 01 '15 at 4:48
source share

The purpose of preallocating and using new Array(n) in addition to good readability is to pre-reserve the memory stack . Then, when we start using the stack, we avoid all the problems of reallocating memory and reallocating and copying items .

I do not know about the implementation of engines and processing for automatic distribution. And how optimized it is. But usually they allocate a little more than what they initialized, then when we reach the end , they redistribute with a large size (following some policy). And so on. So use push, unshift ... etc. May greatly affect performance .

Of course, I did not say how we can optimize and use new Array(n) ?
The answer is simple. It manages the stack independently , as in regular arrays in c or c ++ . The goal is to allow the engines to activate the implemented optimization mechanisms there. Which basically solves the issue of creating an optimized constant binary machine code (in many cases, the performance in such blocks will be equivalent to or close to the performance of the code written in c / c ++). What is the work of the jit compiler (just in time) and its optimization kit .

In our case, all this will translate to the use of normal arrays instead of dynamic vectors . And the issue of freeing, redistributing, and copying will also be fixed .

To better understand, I propose this golden article that examines various ways to optimize arrays.

gold article .

And this is a video that explains and demonstrates how v8 performs some optimization and how important little things are. https://www.youtube.com/watch?v=p-iiEDtpy6I

Bonus Note

And finally, remember that you do not need to optimize until it matters, and it matters .

If you are working in a regular application, without much benefit or importance, it will not matter (a good example is reactive structures, such as reaction, redistribution always exists, (immutable elements), but it does not matter, and In case we need to optimize for some reason, we can always do this, and we can apply the above, for example, with some hooks of side effects (all such frames provide simplicity and responsiveness against senseless optimization. With open doors for I am optimizing if necessary.).

And an example, and even in environments where you might think about optimization, is when you have a large dataset or element processing, which involves repetition and processing. An example would be creating a very complex chart module. You can work with it separately from the platform and optimize everything you can. And then wrap it up. We can also mention games, complex treatment and calculations ... etc.

Actual testing and measurement (using your development tool) is very important [this is what actually allows us to notice the difference].

And if some tips are easy to implement, why not make them part of your style and trend.

0
Jun 15 '19 at 6:31
source share

Well, personally, I want a queue. I want the line to be 10 in length.

The easiest way to do this is to use the push array method to place items at the end of the queue and the shift() method to get them from the front of the array.

The problem is that if I want to make a simple “add” method in turn, and I will write it like this:

 function addItemToArray(item, array){ array.shift(); array.push(item); return array; } 

then nothing good will happen. Which is better (actually, that will work) is to declare my array as follows:

 var maxSizeIsTen = new Array(10); 

and then use it everywhere. Also, pay attention to the “good” way of describing the array - no comments that anyone reads, and anyone using this code will determine the maximum size of this array in a short time.

YAY!

-one
Sep 11 '12 at 18:17
source share



All Articles