[英]Memory Size: What's Smallest Between String or Array
var string = '';
var array = [];
for(var i = 0; i < 10000; i++){
string += '0';
array.push(0);
}
Which one would be smaller? 哪一个较小? When/where is the breakpoint between the two?
两者之间的断点何时/何处?
Note: The numbers are always 1 digit. 注意:数字始终为1位数字。
Creating the array is about 50% faster than creating the string. 创建数组比创建字符串快约50%。
Based on the answer here , you can roughly calculate the size of different data-types in JavaScript. 根据此处的答案 ,您可以大致计算JavaScript中不同数据类型的大小。
The equations used, pertaining directly to your question, to calculate the size in bytes: 直接与您的问题有关的方程式,用于计算字节数:
string = string.length * 2
number = 8
Based on this, the size of your array
variable would depend on the content-type being placed in it. 基于此,
array
变量的大小将取决于放置在其中的内容类型。 As you're inserting numeric values, each offset would be 8 bytes, so: 当您插入数值时,每个偏移量将是8个字节,因此:
array[number] = array.length * 8
With these equations, the sizes are: 使用这些等式,大小为:
string = 20000
array = 80000
If you were to use array.push('0')
instead (ie use strings), the sizes of string
and array
should be roughly equal. 如果要改用
array.push('0')
(即使用字符串),则string
和array
的大小应大致相等。
References: 参考文献:
The String Type - EMCAScript Language Specification : 字符串类型-EMCAScript语言规范 :
The String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values.
字符串类型是零个或多个16位无符号整数值的所有有限有序序列的集合。
The Number Type - EMCAScript Language Specification : 数字类型-EMCAScript语言规范 :
The Number type has exactly 18437736874454810627 (that is, 264−253+3) values, representing the double-precision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic
Number类型正好具有18437736874454810627(即264-253 + 3)值,表示双精度64位格式IEEE 754值,如IEEE二进制浮点算术标准中所指定
To store small numbers in an array, best way is to use a Int8Array. 要在数组中存储小数字,最好的方法是使用Int8Array。
( https://developer.mozilla.org/en-US/docs/Web/API/Int8Array ). ( https://developer.mozilla.org/en-US/docs/Web/API/Int8Array )。
The array will be faster always. 阵列将始终更快。
With the string, each time you append, the runtime has to allocate space for the new string, and then throw away the last version of the string. 对于字符串,每次添加时,运行时都必须为新字符串分配空间,然后丢弃该字符串的最后一个版本。
With the array, it's just extending a linked list. 有了数组,它只是扩展了一个链表。
http://en.wikipedia.org/wiki/Linked_list http://en.wikipedia.org/wiki/Linked_list
On the other hand, the string will probably consume less memory since all the data will be in a single contiguous block of RAM, whereas the array will have the data and all the linked-list pointers too. 另一方面,该字符串可能会消耗较少的内存,因为所有数据都将位于单个连续的RAM块中,而该数组也将具有数据和所有链接列表指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.