有效地将byte []转换为字符串

时间:2014-01-08 17:00:03

标签: c# io

我正在开发一个业余爱好项目(简单/高效的数据存储区)。我目前关注的是从磁盘读取数据(二进制)和填充对象的性能。

我的目标是创建一个针对读取性能(针对移动设备)进行优化的简单存储,这比从SQL数据库或CSV读取要快得多。

在分析应用程序之后,当我从磁盘读取数据(~1000条记录= 240毫秒)时,大部分时间记录在方法“set(byte [])”中:

// data layout:
// strings are stored as there UTF-8 representation in a byte array
// within a "row", the first two bytes contain the length in bytes of the string data
// my data store also supports other types (which are much faster) - not shown below.
class myObject : IRow
{
  public string Name;
  public string Title;
  // and so on
  public void set(byte[] row_buffer)
  {
     int offset = 0;
     short strLength = 0;

     // Name - variable about 40 bytes 
     strLength = BitConverter.ToInt16(row_buffer, offset);
     offset += 2;
     Name = Encoding.UTF8.GetString(row_buffer, offset, strLength);
     offset += strLength;

     // Path - variable about 150 bytes
     strLength = BitConverter.ToInt16(row_buffer, offset);
     offset += 2;
     Path = Encoding.UTF8.GetString(row_buffer, offset, strLength);
     offset += strLength;

     // and so on
  }
}

进一步评论:

  • 数据从磁盘读取为二进制文件。
  • 对于文件中的每一行,创建一个新对象并调用函数集(row_buffer)。
  • 将流读入row_buffer(使用br.Read(row_Buffer,0,rowLengths [i]))占用约10%的时间
  • 将字节(GetString)转换为字符串消耗大约88%的时间

- >我不明白为什么创建字符串是如此昂贵:(

任何想法,我如何才能提高性能?我仅限于“安全C#”代码。

感谢阅读。

修改

我需要创建对象来运行我的Linq查询。我想推迟创建对象,但在这个阶段找不到方法。请参阅我的其他问题:Implement Linq query on byte[] for my own type

0 个答案:

没有答案