yazanpro
yazanpro

Reputation: 4762

Javascript Array Arbitrary Index Memory Allocation

is declaring an array and initializing some arbitrary indexes allocate all the array elements in the memory even the undefined ones?

Example:

var users = [];

function addUser(userID, name, address) {
   if (typeof (users[userID]) === 'undefined')
       users[userID] = new User(userID, name, address)
}

function User (userID, name, address) {
    this.userID = userID;
    this.name = name;
    this.address = address;
}

$(function () {
   addUser(63, 'John', 'VA');
   addUser(5, 'Kate', 'NY');
   addUser(895, 'Yaz', 'DC');
});

So in the above example, will the browser allocate 896 instances of User in the memory (only 3 are defined) or only 3?

Thanks,

Upvotes: 1

Views: 436

Answers (1)

Mulan
Mulan

Reputation: 135227

Nope

JavaScript doesn't care what you put in the array, and it's not going to auto-populate it with values you didn't give it.

If you add 3 users to the array, you will only have 3 users in memory.

The indices in the gaps will just be undefined


var x = [];
// undefined

x[0] = "user1";
// 'user1'

x[3] = "user2";
// 'user2'

x[10] = "user3";
// 'user3'

x;
// ['user1',,,'user2',,,,,,,'user3']

All of that said, you might be better off using an Object ({})

var users = {};

function addUser(userID, name, address) {
  if (!(userID in users)) {
    users[userID] = new User(userID, name, address)
  }
}

You will have an object that looks like this

{"63": [object User], "5": [object User], "895": [object User]}

Upvotes: 1

Related Questions