blob-to-buffer icon indicating copy to clipboard operation
blob-to-buffer copied to clipboard

Use Response or blob.arrayBuffer() instead of FileReader

Open steelbrain opened this issue 9 years ago • 8 comments

There is a significant performance difference. Ref: https://jsperf.com/array-buffer-blob

steelbrain avatar Nov 03 '15 09:11 steelbrain

Thanks for opening this issue. However, this jsperf just shows that converting from Buffer to Blob (the opposite of what this package does) is faster.

There's no way (that I know of) to convert from Blob to Buffer without FileReader.

feross avatar Nov 21 '15 13:11 feross

There's no way (that I know of) to convert from Blob to Buffer without FileReader.

here is a way:

const buffer = await new Response(blob).arrayBuffer().then(ab => Buffer.from(ab))
const buffer = await new Response(blob).arrayBuffer().then(Buffer.from)

Response are able to convert more then just blob's, it supports arrayBuffer, string, ReadableStream, typed arrays. Anything else not understood by the response constructor will be casted to string then converted into a buffer

jimmywarting avatar Sep 06 '18 10:09 jimmywarting

Neat, this didn't exist in 2015. Does this actually perform better than FileReader? It's going to be way less browser compatible too.

feross avatar Sep 12 '18 01:09 feross

I don't know if it is faster or slower. Using response means no support for IE, it doesn't have the fetch api. What I like about this is that you can also get a stream from a blob using new response(blob).body

jimmywarting avatar Sep 12 '18 01:09 jimmywarting

Here's a comparison

https://jsperf.com/blob-to-arraybuffer

KayleePop avatar Dec 22 '18 22:12 KayleePop

there is a new reading methods on the horizon coming to your browser soon

blob.arrayBuffer() blob.text() blob.stream()

jimmywarting avatar Apr 20 '19 08:04 jimmywarting

@KayleePop Thanks for making that performance test. Here were my results:

Screen Shot 2019-08-12 at 6 25 56 PM

Seems like the Response approach is faster for large files. Am I reading that, right?

@jimmywarting It seems that .arrayBuffer() is already available in Chrome and Firefox in my testing. Not in Safari, though. I didn't test Edge because it's switching to Chromium anyway soon.

I would accept a PR to migrate this library to use the Response approach, since I already switched it to using promises in the last major update.

If we do a performance test of .arrayBuffer() and find it's faster than the Response approach, it might be worth feature-detecting it and using it when it's present.

feross avatar Aug 13 '19 01:08 feross

Blob.arraybuffer just got introduced to latest Chrome version v76

jimmywarting avatar Aug 13 '19 07:08 jimmywarting