2014년 12월 26일 금요일

Very simple question re:Buffers...

please tell me what I am missing here. The doc (http://nodejs.org/api/buffer.html#buffer_buf_slice_start_end) for Buffer#slice says:

=========

buf.slice([start], [end])

• start Number, Optional, Default: 0
• end Number, Optional, Default: buffer.length

Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes.

=========

Given that offsets are 0-indexed and [end] is the end offset, shouldn’t that default to buffer.length - 1? Digging through node/lib/buffer.js to smalloc, I see:

  size_t length = end - start;

i.e., the ‘end’ is not really used as an offset of the end, in calculating the length. So I am guessing the underlying implementation is safe (which it would be given Buffer is not new!), so if I am at all right, this is a documentation *interpretation* issue?


P.S: given that the new buffer references the same memory, I am assuming this is an extremely cheap operation. True?




The use and definition of 'end' is likely to be the same as for TypedArray.subarray(start,end)  or  Array.slice(start,end)  where the JS docs are careful to say "end - Element to end at. The offset is exclusive (i.e. outside of)  If not specified, all elements from the one specified by begin to the end of the array are included in the new view."

So 'end' is the index just beyond the end of the area you want to grab.  And yes, (end - start) gives you exactly the length to use, because end is one past the end of the area you want.

As to the other half of your question, don't know...  :-(




Given that offsets are 0-indexed and [end] is the end offset, shouldn’t that default to buffer.length - 1? Digging through node/lib/buffer.js to smalloc, I see:

`end` is the ending offset (not inclusive).
P.S: given that the new buffer references the same memory, I am assuming this is an extremely cheap operation. True?


It doesn't allocate memory, but it does have to create a new Buffer object (to represent the slice). Doing so does not come without some cost, but in most cases this overhead does not cause problems. Performance issues are likely to be elsewhere before Buffer instantiation becomes your bottleneck.


댓글 없음:

댓글 쓰기