En lugar de leer y escribir un carácter a la vez, leer y escribir todos a la vez:
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;
Ahora, técnicamente, ya que WideString
es un Windows BSTR
, lo que puede contiene un número impar de de bytes. La función Length
lee el número de bytes y los divide por dos, por lo que es posible (aunque no probable) que el código anterior corte el último byte. Se podría utilizar este código en su lugar:
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;
Inspirado por Mghie's answer, han reemplazado a mis Read
y Write
llamadas con ReadBuffer
y WriteBuffer
. Este último levantará excepciones si no pueden leer o escribir el número solicitado de bytes.
Cambiar un área particular de su código porque * beli Eva * puede ser el cuello de botella puede ser una gran pérdida de tiempo. Primero debe medir, hay muchas herramientas para ayudarlo, algunas gratis, algunas comerciales. Pruebe estos primero para algunos enlaces: http://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi y http://stackoverflow.com/questions/368938/delphi-profiling-tools – mghie
Gracias, pero estaba usando QueryPerformanceCounter para detectar eso;) de todos modos ese fue el cuello de botella seguro, ya que leer char por char es muy lento ... todas las demás operaciones solo guardaban algunos datos binarios cortos. – migajek
Ah, está bien.Estaba reaccionando sobre el uso de las palabras "creer" y "poder", perdón por la predicación ;-) – mghie