Reputation: 3608
I have a look at the Node.js Buffer documentation and I don't understand the difference between Buffer.slice and Buffer.subarray.
Both point to "the same memory as the original".
But no one seems not to be the alias of the other (it seems to be said when it is the case).
And test says that behavior is the same :
> buf=Buffer.from([0,1,2,3,4,5,6])
<Buffer 00 01 02 03 04 05 06>
> bufSlice=buf.slice(1,5)
<Buffer 01 02 03 04>
> bufSub=buf.subarray(1,5)
<Buffer 01 02 03 04>
> bufSlice
<Buffer 01 02 03 04>
> bufSub
<Buffer 01 02 03 04>
> buf[3]=0xff
255
> buf
<Buffer 00 01 02 ff 04 05 06>
> bufSub
<Buffer 01 02 ff 04>
> bufSlice
<Buffer 01 02 ff 04>
(even if example of slice in Node.js documentation is not very clear).
So what's the difference ?
Upvotes: 16
Views: 11751
Reputation: 553
According to https://nodejs.org/api/buffer.html#bufsubarraystart-end, and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice,
Buffer.subarray()
is a buffer view that does not need to create an extra copy of the underlying buffer. This makes subarray()
much more efficient than slice()
, which does create a copy.
Upvotes: -1
Reputation: 2066
For a NodeJS Buffer
there is no difference and indeed Buffer.slice()
is deprecated now so you should use Buffer.subarray()
.
This deprecation was presumably done because NodeJS Buffer.slice()
was inconsistent with other slice
calls in JS, e.g.:
const t = Buffer.from([1])
t.slice()[0]=2
console.log(t[0]) // logs 2, i.e. `slice` uses same underlying memory, like `subarray` does
const t2 = [1]
t2.slice()[0]=2
console.log(t2[0]) // logs 1, unchanged! I.e. `slice` copied underlying memory
const t3 = new Uint8Array([1])
t3.slice()[0]=2
console.log(t3[0]) // logs 1, unchanged! I.e. `slice` copied underlying memory
Upvotes: 7
Reputation: 3608
Buffer.slice
is now deprecated (since node 16.x LTS)
So now use Buffer.subarray
!
Upvotes: 8