[英]Fastest way to convert any string to array in javascript
我目前正在用Javascript开发一个GameBoyColor模拟器。
将64k ROM文件加载到内存单元大约需要60秒。 这是功能:
loadROM: function (file) {
var reader = new FileReader();
reader.onload = function () {
var start = new Date();
console.log("start", start.getTime());
this.__ROM = new Uint8Array(reader.result.length);
for (var i = 0; i < reader.result.length; i++) {
this.__ROM[i] = (reader.result.charCodeAt(i) & 0xFF);
}
var end = new Date();
console.log("end", end.getTime());
console.log((end.getTime() - start.getTime()) + " for " + i + " iterations");
this._trigger("onROMLoaded");
}.context(this);
reader.readAsBinaryString(file);
}
reader.result
是ROM文件的字符串, this.__rom
是数组。 重要的是for循环,我获取每个字符并将其推送到内存的ROM数组。
这需要很长时间。 所以问题是如何加速这件事。 有没有更好的方法将字符串转换为数组?
您应该能够使用split()
而不是循环来本机执行:
// See the delimiter used
this.__ROM = reader.result.split('');
// And to do the bitwise AND on each byte, use map()
this.__ROM = this.__ROM.map(function(i) {
return i & 0xFF;
});
或者一步(没有写入this.__ROM
两次):
this.__ROM = reader.result.split('').map(function(i) {
return i & 0xFF;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.