In a function that reads data (data meaning exclusively strings) from disk, which should I prefer? Which is better?
A) DiskStream.Read(Pointer(s)^, Count)
or
B) DiskStream.Read(s[1], Count)
Note:
I know both are having the same result.
I know that I have to SetLength of S before calling Read.
UPDATE
S is AnsiString.
Here is the full function:
{ Reads a bunch of chars from the file. Why 'ReadChars' and not 'ReadString'? This function reads C++ strings (the length of the string was not written to disk also). So, i have to give the number of chars to read as parameter. }
function TMyStream.ReadChars(out s: AnsiString; CONST Count: Longint): Boolean;
begin
SetLength(s, Count);
Result:= Read(s[1], Count)= Count;
end;
Speed test
In my speed test the first approach was a tiny bit faster than the second one. I used a 400MB file from which I read strings about 200000 times. The process was set to High priority.
The best read time ever was:
1.35 for variant B and 1.37 for variant A.
Average:
On average, B was scoring also 20ms better than A.
The test was repeated 15 times for each variant.
The difference is really small. It could fall into the measuring error range. Probably it will be significant if I read strings more often and from a bigger file. But for the moment let's say that both lines of code are performing the same.
ANSWER
Variant A - might be a tiny tiny bit faster
Variant B - is (obviously) much more easier to read and it is more Delphi-ish. My preferred.
Note:
I have seen Embarcadero using variant A in TStreamReadBuffer example, but with a TBytes instead of String.