6

I want to modify an ArrayBuffer's contents in JavaScript.

From the help section:

You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

I don't need to print anything to console, I just need an ArrayBuffer with some bytes modified.

So, if I have a large ArrayBuffer:

const buffer = new ArrayBuffer(16*1024);

Which one is more effective:

const typedArray1 = new Uint8Array(buffer);
typedArray1[16000] = 65;

const typedArray2 = new Uint8Array(buffer,16000);
typedArray2[0] = 65;

const typedArray3 = new Uint8Array(buffer,16000,1);
typedArray2[0] = 65;

const dataView1 = new DataView(buffer);
dataView1.setUint8(16000, 65);

const dataView2 = new DataView(buffer, 16000);
dataView2.setUint8(0, 65);

const dataView3 = new DataView(buffer, 16000, 1);
dataView3.setUint8(0, 65);
7
  • The TypedArray value settings operations are more straightforward than DataView. I'd imagine you'd create some overhead with the sliced versions, but nothing more will be allocated in memory in any of these cases, so if it's a one shot, you won't be able to measure any meaningful difference in any of these. So the real question is, "do you experience a real bottleneck where this decision may have an impact?". Remember a TypedArray view costs nothing. Commented Mar 11, 2020 at 7:06
  • So you are saying that typedArray1 is the best way to go? Commented Mar 11, 2020 at 9:58
  • I'm saying that it won't matter in this case. But yes, generally speaking it should theoretically be the "most efficient" one. Commented Mar 11, 2020 at 10:00
  • 2
    v8.dev/blog/dataview - here they show that currently (2018) dataview was 4 times slower than typedarray. Just found this. Anyway the close vote "needs details or clarity" seems unfair. :) Commented Mar 11, 2020 at 10:00
  • 2
    Aha. "I just need an ArrayBuffer with some bytes modified" - that is the case, which I believe describes the use case: I don't need either DataView, nor TypedArray. It's just a must based on ArrayBuffer's spec and I wanted to know which one is better in terms of performance. There are always differences in performance and usually community is very good in these questions. You've said all 6 are very similar, but I found a site which states huge differences in between - that's why it feels unfair. Even though these diffs might already have disappeared. Commented Mar 11, 2020 at 10:17

0

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.