Memory allocation of a Javascript array?

前端 未结 3 863
说谎
说谎 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: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

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题