如何强制JavaScript深度复制字符串?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (492)

有一些javascript代码,如下所示:

var myClass = {
  ids: {}
  myFunc: function(huge_string) {
     var id = huge_string.substr(0,2);
     ids[id] = true;
  }
}

提问于
用户回答回答于

JavaScript的ECMAScript实现因浏览器而异,但对于Chrome,许多字符串操作(substr,slice,regex等)只保留对原始字符串的引用,而不是复制字符串。这是Chrome中的一个已知问题要强制使用该字符串的副本,以下代码可以正常工作:

var string_copy = (' ' + original_string).slice(1);

警告:需要很长时间才能加载,打开Chrome调试控制台以查看进度打印输出

// We would expect this program to use ~1 MB of memory, however taking
// a Heap Snapshot will show that this program uses ~100 MB of memory.
// If the processed data size is increased to ~1 GB, the Chrome tab
// will crash due to running out of memory.

function randomString(length) {
  var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = 0; i < length; i++) {
    result +=
        alphabet[Math.round(Math.random() * (alphabet.length - 1))];
  }
  return result;
};

var substrings = [];
var extractSubstring = function(huge_string) {
  var substring = huge_string.substr(0, 100 * 1000 /* 100 KB */);
  // Uncommenting this line will force a copy of the string and allow
  // the unused memory to be garbage collected
  // substring = (' ' + substring).slice(1);
  substrings.push(substring);
};

// Process 100 MB of data, but only keep 1 MB.
for (var i =  0; i < 10; i++) {
  console.log(10 * (i + 1) + 'MB processed');
  var huge_string = randomString(10 * 1000 * 1000 /* 10 MB */);
  extractSubstring(huge_string);
}

// Do something which will keep a reference to substrings around and
// prevent it from being garbage collected.
setInterval(function() {
  var i = Math.round(Math.random() * (substrings.length - 1));
  document.body.innerHTML = substrings[i].substr(0, 10);
}, 2000);
用户回答回答于

下面是允许我复制字符串并在数组结果中获取唯一值的内容:

while (results.next()) {
  var locationName = String(results.name);
  myArray.push(locationName);
}

扫码关注云+社区

领取腾讯云代金券