[英]Fastest way to convert any string to array in javascript
I'm currently developing a GameBoyColor emulator in Javascript. 我目前正在用Javascript开发一个GameBoyColor模拟器。
Loading a 64k ROM file into the Memory Unit takes about 60 seconds right now. 将64k ROM文件加载到内存单元大约需要60秒。 This is the function:
这是功能:
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
is the ROM file as string and this.__rom
is the array. reader.result
是ROM文件的字符串, this.__rom
是数组。 Important is the for loop where I get every single character and push it to the ROM array of the memory. 重要的是for循环,我获取每个字符并将其推送到内存的ROM数组。
This takes way to long. 这需要很长时间。 So question is how to speed this thing up.
所以问题是如何加速这件事。 Is there any better approach to convert a string into an array?
有没有更好的方法将字符串转换为数组?
You should be able to do it natively using split()
instead of looping: 您应该能够使用
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;
});
Or in one step (without writing to this.__ROM
twice): 或者一步(没有写入
this.__ROM
两次):
this.__ROM = reader.result.split('').map(function(i) {
return i & 0xFF;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.