Memory allocation of a Javascript array?

前端 未结 3 861
说谎
说谎 2021-01-25 11:10

If I add a value to the 1000th element of a Javascript array, then is there any difference to adding that value to the 0th element assuming those positions are open?

I\'

相关标签:
3条回答
  • 2021-01-25 11:29

    JavaScript objects don't really have an ordering, per se. Whether they're Arrays or Objects, the order of the keys isn't considered important; an implementation can put them in whatever order it wants. Of course, you have to store them in some kind of order, and so most implementations keep them in the order you inserted them in. But this is only a coincidence: the specs do not mandate it, and so you can't count on it always being true.

    Because of this, arr[1000] isn't necessarily the 1000th element of the array: it's just a member with a key that happens to be 1000. It might indeed be the 1000th element, if you inserted 999 elements before it and your runtime keeps them in insertion order. But it could just as easily be, say, the 42nd element. It might even be the very first element, depending on both the runtime's implementation and your own code.

    And since Arrays don't have an ordering, assigning to arr[1000] doesn't take up any more memory than assigning to arr[0], assuming that nothing else has been set yet. If you've already set 999 elements, then obviously setting arr[1000] will cause the array to take up a little more space than before, because you've got to store that element somewhere. But it doesn't take up any additional space just because its key is 1000.

    0 讨论(0)
  • 2021-01-25 11:31

    If you have an array of size 1000, you are taking up 1000 slots in memory.

    var arr = new Array(1000);

    The time complexity is still constant for array lookups, so that is not going to slow down your application.

    However, you are explicitly asking for 1000 slots in memory, so it's still a sizeable piece of space. While memory, as hardware, is cheap, you should still aim to keep your arrays dynamic in size whenever possible to prevent your program from taking up unnecessary space in memory.

    0 讨论(0)
  • 2021-01-25 11:43

    Due to JavaScript arrays actually being objects, memory is not contiguous. Thus, by your example, accessing array[1000] without ever storing anything elsewhere will take the same amount of memory as whatever you're storing (not 1000 * size of value).

    In fact, doing var arr = new Array(1000); per Danny's answer does not create an array of 1000 empty slots. It creates an array with a length property of the value 1000.

    Think about it this way: How is JavaScript to know how much memory to set aside if it doesn't know the type and size of what it's storing?

    For example:

    var arr = [];
    arr[1000] = 'String value';
    

    What's saying I can't come by and store an integer at another index?

    arr[0] = 2;
    

    Source: https://stackoverflow.com/a/20323491/2506594

    0 讨论(0)
提交回复
热议问题