feross / blob-to-buffer

Convert a Blob to a Buffer.
MIT License
76 stars 13 forks source link

Use Response or blob.arrayBuffer() instead of FileReader #1

Open steelbrain opened 9 years ago

steelbrain commented 9 years ago

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

feross commented 8 years ago

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.

jimmywarting commented 6 years ago

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

feross commented 6 years ago

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

jimmywarting commented 6 years ago

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

KayleePop commented 5 years ago

Here's a comparison

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

jimmywarting commented 5 years ago

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

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

feross commented 5 years ago

@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.

jimmywarting commented 5 years ago

Blob.arraybuffer just got introduced to latest Chrome version v76