The fastest way to convert any string to an array in javascript

I am currently developing a GameBoyColor emulator in Javascript.

Downloading a 64-bit ROM file to a memory block takes about 60 seconds. 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 a ROM file as a string, and this.__rom is an array. The for loop is important, where I get each individual character and paste it into an array of ROM memory.

It lasts a long time. So the question is how to speed up this business. Is there a better way to convert a string to an array?

+4
source share
1 answer

You can do this initially using split() instead of a loop:

 // 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; }); 
+5
source

Source: https://habr.com/ru/post/1485393/


All Articles