/    Sign up×
Community /Pin to ProfileBookmark

Declare a large Array in javascript indicating its size.

In a web page that uses javascript I need to maximize the speed with which it is filled
an array (myArray).

The way I will use to do this is summarized with the following example, which fills an Array of integers
called Array1:

1) The usual way to enter elements in Array1 is:
var Array1 = [5,7];
Array1.push (10);

2) But if I know a priori the size I will need for the Array, it is much faster to do so:
var Array1 = [0, 0, 0, 0, 0]; // Allocated array of length 5.
var A1Length = 0;
// to do a ‘push’, do
Array1 [A1Length ++] = 10;

However, the Array that I am using on my website (myArray) does not contain integers, but objects
each of which is an Array of two elements.
It is not a two-dimensional Array, but an array that contains Array objects.
I will use it as a map where “A” is the key and “B” is the value that I am looking for.

Currently, I fill it like this and it works correctly:
var myArray = [];
var newElement = {“A”: 10, “B”: ‘Name 1’}
myArray.push (newElement);

To increase the speed with which myArray is filled, following the example discussed for Array1,
I need to declare it with the size it will have (1000 Array objects of two dimensions).

I have tried to declare it like this:
var myArray = Array.from (Array (1000), () => new Array (2));
var myArrayUsed = 0;

And then insert new elements in it:
var newElement = {“A”: 10, “B”: ‘Name 1’}
myArray [myArrayUsed ++] = newElement;

The problem is that this code does not work and I think it is because myArray declaration statement
is not correct.

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumNov 19.2019 — Interesting subject. I never heard about your second procedure being faster than the first one but a short research confirmed it. I didn' t dive into this deeply but I think that you should create your array like this:

` var myArray = Array.from(Array(1000), () => { return { "A": 0, "B": ' ' }; });`

However I'm not shure if this will help as the the array is iterated through twice now, the first time when creating it and the second time when filling it with the final values.
×

Success!

Help @jstechg spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...