Why lodash cloneBuffer function use buffer.slice when isDeep flag is true?

Viewed 84

Here is the loadsh source code:

function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice()
  }
  const length = buffer.length
  const result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length)

  buffer.copy(result)
  return result
}

As we can see, if the isDeep flag is true,cloneBuffer function use buffer.slice() to copy the buffer.

But accord to the Node.js slice's documents:

Returns a new Buffer that references the same memory as the original

https://nodejs.org/docs/latest-v13.x/api/buffer.html#buffer_buf_slice_start_end

And Buffers and TypedArrays documents:

While TypedArray#slice() creates a copy of part of the TypedArray, Buffer#slice() creates a view over the existing Buffer without copying.

https://nodejs.org/docs/latest-v13.x/api/buffer.html#buffer_buffers_and_typedarrays

Which said it clearly, Buffer.slice just creates a view over the existing Buffer, and without copying.

so why lodash use it to do the cloneDeep operation?

0 Answers
Related