而不是读取和写一次一个字符,同时读取和写入他们都:
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