1

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

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. Commented Sep 24, 2014 at 13:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

And also set it via array.length
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?
Yeah, it would. But as mentioned, it is probably not necessary.
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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.