Welcome to the Linux Foundation Forum!

Buffers: subarray & slice

In the course material for Buffers, there is mention and usage of slice.
in the Nodejs.dev site that discusses Buffers they make use of subArray.
When should we use one or the other? are they interchangeable?

Best Answer

Answers

  • I want to follow up that I went and read on and found this great link:
    http://shockry.blogspot.com/2017/04/javascript-typed-arrays-slice-vs.html

    From that page:

    slice: Allocate a new space in memory and copy the items from the original array between the start and end indices provided in the arguments into these new memory locations, return the new array.

    subarray: make a new empty typed array object, which points to a part of the original array between the start and end indices provided in the arguments.

    Minor difference!

    ... (continued)... So basically subarray lets a and c see and modify the same memory locations, it provides a smaller "view" (window) over the original array.

  • array and typed array slice and buffer slice are different. Array and typed array slice creates a new array from a slice of the array it's called on. Buffer, even though it's based on Uint8Array, overrides the slice method so that the slice is actually a reference to an internal part of that buffer (for legacy and performance reasons)

Categories

Upcoming Training