最佳缓冲流写入过程 [英] Optimal Buffer Stream write process

查看:71
本文介绍了最佳缓冲流写入过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有自己的数据流算法,其中包括一些元数据+记录+字段值。

We have our own data streaming algorithm that include some metadata+records+fields values.

当前,我们使用TStream并编写将值添加到流中。
现在我想知道是否可以通过使用某些技术来使这次加法运算更快。

Currently we use a TStream and write to add values to the stream. Now I'm wondering if this time cosuming operation could be made faster by using some technic.

编辑:

我在想的一些事情是:


  • 不使用Streams buf分配一些大的内存分配缓冲区来复制数据,问题是如果我们超出缓冲区大小,则必须重新定位到一些新的内存空间。

  • 使用预填充#0到一定大小的流,然后开始添加值。理由是Tstream每次执行写操作时都必须分配它自己的缓冲区(我不知道它的真正工作原理,只是想知道...)

我们将字符串添加到TStream中,并以#0#0#0#1的形式添加二进制数据。

We are adding strings to the TStream and binary data in the form #0#0#0#1 for example.

然后将数据通过TCP传输,因此与写文件无关。

The data is then transfered via TCP, so it's not about write to a File.

那么,最佳方法是什么?

So what is the best method for this?

推荐答案

覆盖TMemoryStream并消除对大小和容量的限制。并且不要调用TMemoryStream.Clear而是调用TMemoryStream.SetSize(0)

Overwrite TMemoryStream and remove the restriction of Size and Capacity. And do not call TMemoryStream.Clear but call TMemoryStream.SetSize(0)

type
  TMemoryStreamEx = class(TMemoryStream)
  public
    procedure SetSize(NewSize: Longint); override;
    property Capacity;
  end;

implementation

{ TMemoryStreamEx }

procedure TMemoryStreamEx.SetSize(NewSize: Integer);
var
  OldPosition: Longint;
begin
  if NewSize > Capacity then
    inherited SetSize(NewSize)
  else
  begin
    OldPosition := Position;
    SetPointer(Memory, NewSize);
    if OldPosition > NewSize then
      Seek(0, soFromEnd);
  end;
end;

这篇关于最佳缓冲流写入过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆