Javascript数组的内存分配? [英] Memory allocation of a Javascript array?

查看:56
本文介绍了Javascript数组的内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Javascript数组的第1000个元素中添加一个值,那么假设这些位置是开放的,那么将该值添加到第0个元素有什么区别吗?

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?

我说的是内存消耗.

示例:

arr[1000] = 'asdf';

arr[0] = 'asdf';

推荐答案

由于JavaScript数组实际上是对象,因此内存不是连续的.因此,以您的示例为例,访问array[1000]而不存储任何其他内容将占用与您存储的内容相同的内存量(而不是1000 *值的大小).

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).

实际上,按照Danny的答案进行var arr = new Array(1000);并不会创建1000个空插槽的数组.它创建一个数组,数组的length属性值为1000.

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.

这样想:如果不知道存储的类型和大小,JavaScript如何知道要留出多少内存?

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?

例如:

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

这是什么意思,我不能在另一个索引中存储整数?

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

arr[0] = 2;

来源: https://stackoverflow.com/a/20323491/2506594

这篇关于Javascript数组的内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆