12

I have a WebSocket that receives binary messages and I want iterate over the bytes.

I came up with the following conversion function...

// Convert the buffer to a byte array.
function convert(data, cb) {
    // Initialize a new instance of the FileReader class.
    var fileReader = new FileReader();
    // Called when the read operation is successfully completed.
    fileReader.onload = function () {
        // Invoke the callback.
        cb(new Uint8Array(this.result));
    };
    // Starts reading the contents of the specified blob.
    fileReader.readAsArrayBuffer(data);
}

This does work, but the performance is terrible. Is there a better way to allow reading bytes?

2
  • What is the browser you are using? Commented Aug 1, 2013 at 9:42
  • Google Chrome is the browser I am using. Commented Aug 1, 2013 at 9:52

1 Answer 1

24

Have you considered:

socket.binaryType = 'arraybuffer';

The function becomes:

function convert(data) {
     return new Uint8Array(data);
}

Which will not actually have to do any work because it's just a view on the buffer.

Sign up to request clarification or add additional context in comments.

1 Comment

Massive improvement in terms of maintainability AND performance. Great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.