Is there an equivalent method in Javascript arrays or ArrayList to Java's ensureCapacity? I am translating a certain Java code containing this method to Javascript, and couldn't find any equivalent to it. Thanks in advance
Asked
Active
Viewed 123 times
1
-
No, there is no official one, but engines are pretty smart anyway. Some of them have an optimisation to pre-allocate memory when you assign a `.length`, but it doesn't make much difference. – Bergi Sep 24 '14 at 13:59
2 Answers
1
It is possible to initialize an array with a specific size:
var array = new Array(n);
If your array has already been initialized you can, as mentioned in comments, set the length of the array using the length
property:
array.length = n;
However, the performance gains, if any, seems negligble. Here is a thread discussing this.

Community
- 1
- 1

Frederik Wordenskjold
- 10,031
- 6
- 38
- 57
-
1
-
So, for instance, if I am using it this way: public Path(int initialCapacity) { tsIindexes.ensureCapacity(initialCapacity); tsJindexes.ensureCapacity(initialCapacity); } would setting it with length amount to the same thing as done here? – elbereth Sep 24 '14 at 13:32
-
Yeah, it would. But as mentioned, it is probably not necessary. – Frederik Wordenskjold Sep 24 '14 at 13:48
0
var fruits = ['apple', 'pineapple'];
console.log(fruits.length, fruits);//2 ["apple", "pineapple"]
fruits.length = fruits.length + 4; //increase by 4
console.log(fruits.length, fruits);//6 ["apple", "pineapple"]
Open console for more ...