在javascript中将任何字符串转换为数组的最快方法(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数组。

这需要很长时间。 所以问题是如何加速这件事。 有没有更好的方法将字符串转换为数组?

I'm currently developing a GameBoyColor emulator in Javascript.

Loading a 64k ROM file into the Memory Unit takes about 60 seconds right now. 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. Important is the for loop where I get every single character and push it to the ROM array of the memory.

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?

最满意答案

您应该能够使用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; });

You should be able to do it natively using split() instead of looping:

// 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 = reader.result.split('').map(function(i) { return i & 0xFF; });

更多推荐