iobuffer
iobuffer copied to clipboard
Do not copy data in readArray when possible
To avoid copying data (using slice), the TypedArray can be created with the arrayBuffer. However it handles only when start offset is a multiple of its type bytes occupancy (otherwise it will trigger similar error : start offset of Int16Array should be a multiple of 2
). I'll use it when it is possible.
However, since the data is not longer copied, this could have bad consequences if a depend library modified the read data.
I also move line const slice = this.buffer.slice(offset, offset + bytes);
as in some case the variable is not used (when entering right after in the if condition).
Note that I'm using similar code https://github.com/remmel/volograms-js/blob/92e3166cebe1dcb823291c11ec50dfb226d7dc99/src/BinaryReader.js#L68
Hello! Thank you for the pull request (and sorry it took a bit long to answer you).
It seems indeed useful to have this optimization available, but we'd like to ask you to implement it behind an option. There are at least two reasons that we don't want it by default:
- As you noticed, it can be breaking change if the user modifies the returned array
- If the original buffer is very large, returning a subarray will hold a reference to it and if we keep the subarray after reading everything, the entire data will be kept in memory and cannot be garbage collected.
Proposed signature:
/**
* Creates an array of corresponding to the type `type` and size `size`.
* For example type `uint8` will create a `Uint8Array`.
* @param size - size of the resulting array
* @param type - number type of elements to read
* @param as - Whether to copy the read data or return a view on the original ArrayBuffer. Note that in certain cases such as unaligned offsets, a view cannot be created and it will copy regardless of this option.
*/
public readArray<T extends keyof typeof typedArrays>(
size: number,
type: T,
as: 'copy' | 'view' = 'copy',
): InstanceType<TypedArrays[T]>
Hi! You're right, I didn't though about the 2nd edge case (reformulated: let's say we want to keep forever a subarray of a huge array, with my PR it will keep everything without duplicating/copying the subarray and without my PR it will keep only the duplicated/copied array)