I'm using Delphi7 (non-unicode VCL), I need to store lots of WideStrings inside a TFileStream. I can't use TStringStream as the (wide)strings are mixed with binary data, the format is projected to speed up loading and writing the data ... However I believe that current way I'm loading/writing the strings might be a bottleneck of my code ...
currently I'm writing length of a string, then writing it char by char ... while loading, first I'm loading the length, then loading char by char ...
So, what is the fastest way to save and load WideString to TFileStream?
Thanks in advance
Rather than read and write one character at a time, read and write them all at once:
Now, technically, since
WideString
is a WindowsBSTR
, it can contain an odd number of bytes. TheLength
function reads the number of bytes and divides by two, so it's possible (although not likely) that the code above will cut off the last byte. You could use this code instead:Inspired by Mghie's answer, have replaced my
Read
andWrite
calls withReadBuffer
andWriteBuffer
. The latter will raise exceptions if they are unable to read or write the requested number of bytes.You can also use TFastFileStream for reading the data or strings, I pasted the unit at http://pastebin.com/m6ecdc8c2 and a sample below:
There is nothing special about wide strings, to read and write them as fast as possible you need to read and write as much as possible in one go:
WideStrings contain a 'string' of WideChar's, which use 2 bytes each. If you want to store the UTF-16 (which WideStrings use internally) strings in a file, and be able to use this file in other programs like notepad, you need to write a byte order mark first:
#$FEFF
.If you know this, writing can look like this:
reading can look like this: