gpt4 book ai didi

javascript - 内存大小 : What's Smallest Between String or Array

转载 作者:行者123 更新时间:2023-11-29 19:44:03 25 4
gpt4 key购买 nike

    var string = '';
var array = [];

for(var i = 0; i < 10000; i++){
string += '0';
array.push(0);
}

哪个会更小?两者之间的断点何时/何地?

注意:数字始终为 1 位。

创建数组比创建字符串快大约 50%。

最佳答案

基于answer here ,你可以粗略地计算出 JavaScript 中不同数据类型的大小。

与您的问题直接相关的用于计算字节大小的方程式:

string = string.length * 2
number = 8

基于此,array 变量的大小将取决于放置在其中的内容类型。当您插入数值时,每个偏移量将为 8 个字节,因此:

array[number] = array.length * 8

根据这些等式,尺寸为:

string = 20000
array = 80000

如果您要改用 array.push('0')(即使用字符串),stringarray 的大小应该大致相等。

引用资料:

  1. The String Type - EMCAScript Language Specification :

    The String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values.

  2. The Number Type - EMCAScript Language Specification :

    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

关于javascript - 内存大小 : What's Smallest Between String or Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21169533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com