而不是讀取和寫一次一個字符,同時讀取和寫入他們都:
procedure WriteWideString(const ws: WideString; stream: TStream);
var
nChars: LongInt;
begin
nChars := Length(ws);
stream.WriteBuffer(nChars, SizeOf(nChars);
if nChars > 0 then
stream.WriteBuffer(ws[1], nChars * SizeOf(ws[1]));
end;
function ReadWideString(stream: TStream): WideString;
var
nChars: LongInt;
begin
stream.ReadBuffer(nChars, SizeOf(nChars));
SetLength(Result, nChars);
if nChars > 0 then
stream.ReadBuffer(Result[1], nChars * SizeOf(Result[1]));
end;
現在,在技術上,因爲WideString
是Windows BSTR
,它可以包含一個奇數字節數。 Length
函數讀取字節數併除以2,所以有可能(儘管不太可能)上面的代碼將切斷最後一個字節。你可以使用此代碼來代替:
procedure WriteWideString(const ws: WideString; stream: TStream);
var
nBytes: LongInt;
begin
nBytes := SysStringByteLen(Pointer(ws));
stream.WriteBuffer(nBytes, SizeOf(nBytes));
if nBytes > 0 then
stream.WriteBuffer(Pointer(ws)^, nBytes);
end;
function ReadWideString(stream: TStream): WideString;
var
nBytes: LongInt;
buffer: PAnsiChar;
begin
stream.ReadBuffer(nBytes, SizeOf(nBytes));
if nBytes > 0 then begin
GetMem(buffer, nBytes);
try
stream.ReadBuffer(buffer^, nBytes);
Result := SysAllocStringByteLen(buffer, nBytes)
finally
FreeMem(buffer);
end;
end else
Result := '';
end;
通過Mghie's answer啓發,已經取代了我的Read
和Write
電話與ReadBuffer
和WriteBuffer
。如果後者無法讀取或寫入所請求的字節數,則會引發異常。
更改您的代碼的特定區域,因爲您* beli前夕*這可能是瓶頸可能是一個巨大的浪費時間。你應該先測量一下,有很多工具可以幫助你,有些是免費的,有些是商業的。首先嚐試以下鏈接:http://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi和http://stackoverflow.com/questions/368938/delphi-profiling-tools – mghie 2009-08-30 15:45:22
謝謝,但我使用QueryPerformanceCounter來檢測;)無論如何,這是確定的瓶頸,由char讀char非常慢......所有其他操作都只是保存一些簡短的二進制數據。 – migajek 2009-08-30 17:48:31
啊,好的。我只是對你使用「相信」和「可能」這兩個詞做出了反應,對於這個講道感到抱歉;-) – mghie 2009-08-31 13:59:34