Langweiliges Zeug. Was sonst.
ArrayBuffer <-> Blob <-> BinaryString conversion
You can speed up your javascript encryption stuff by using ArrayBuffers. However, if you want to convert it back to a binary string for other API calls, it’s really slow. At least if you do it by hand using something like
for(var i=0; i< view.length; ++i)
    str += String.fromCharCode(view[i]);
Of course you can somewhat improve it by using a stringbuilder approach, like
function convertFaster(view)
{
    var array = new Array(view.length);
    for(var i=0; i< view.length; ++i)
        array[i] = String.fromCharCode(view[i]);
    return array.join('');
}
However, there is a much faster way using the FileReader API. Although its name implies only usage for files, it takes a Blob as an argument. Since every File is also a Blob, this makes it possible to read Files. But this also means, we can feed it with custom blobs. To make use of this we can convert any ArrayBuffer to a blob by using the brand new BlobBuilder
var buffer = new ArrayBuffer(3)
var array = new Uint8Array(buffer);
var i=0;
array[i++] = 0x48;
array[i++] = 0x69;
array[i++] = 0x21;

var blobBuilder = new BlobBuilder();
blobBuilder.append(buffer);
buffer = null;
var blob = blobBuilder.getBlob();
var fileReader =new FileReader();
fileReader.onload = function (e) {
	//conversion done
};
fileReader.readAsBinaryString(blob);

To convert a binary string to a blob we can again use the BlobBuilder. Append also accept DOMStrings as argument.

Last but not least a nice performance comparison (ArrayBuffer to BinaryString): click me.

Some results with 5000000 bytes on a Core2Duo 6300:

  • Firefox 9.0.1: 884ms vs 89ms
  • Chromium 14.0.835.202: 1886ms vs 101ms

Conclusion: Speedup between 10x and 20x :)

  1. langweiligeszeug posted this