What are possible ways to save string arrays to a stream without using serialization?
I’m particularly interested in strings since their lengths may vary. I also should be able to restore the array from stream.
And, more importantly, I would like to be able to read only slices of an array without reading full array into memory, because potentially my arrays can be huge.
P.S. I know that there exist databases, that I shouldn’t reinvent the wheel, etc, but I have my reasons to opt for hand made solution.
Thank you.
Well, saving data to a stream is serialization; the real trick is: what kind. For example, I assume you’re talking about things like
XmlSerializerorBinaryFormatterthat require you to deserialize the whole thing, but that isn’t always necessary.By writing each string with a length-prefix, you should be able to seek past items you don’t want pretty easily. The other option is to write (separately) an index of offsets, but that is sometimes overkill.
As a basic example,
shere is"jkl", without it reading the entire stream or deserializing the unwanted strings; note that it could be optimized by (for example) using a variable-length encoding for theint(length), which would also fix the current assumption that endianness is the same between reader and writer: