2013-03-28 67 views
0

我有数百个必须用密钥访问的变量。
键的类型是字符串(最多50个字符),数据是字节数组(最大500字节)。
通过密钥访问数据的最快方法

我这样使用:
定义该类型:

type 
    TMyBuf   = array[0..(500-1)] of Byte; 
    TMyKey   = string[50]; 
    TMyBufs   = TDictionary<TMyKey,TMyBuf>; 
var 
    MyBufs  :TMyBufs; 

,并用于:

var vMyBuf  :TMyBuf; 
    vMyData :TBytes ABSOLUTE vMyBuf; 
    vMyDataLen :Word; 
begin 
    List := srvData.Contexts.LockList; 
    SetLength(vMyBuf, 500); 
    try 
     if(List.Count > 0) then begin 
     for i := 0 to List.Count-1 do begin 
      with TMyContext(List[I]) do begin 
      if SetedIdent then begin 
       try 
       vMyBuf:= MyBufs.Items[SeledData]; 
       //extract length of data which stored in two byte 
       vMyDataLen:= (((vMyBuf[1] shl 8)and $FF00) or (vMyBuf[0] and $FF)); 
       Connection.IOHandler.Write(vMYData, vMYDataLen); 
       finally 
       end; 
      end; 
      end; 
     end; 
     end; 
    finally 
     srvData.Contexts.UnlockList; 
     SetLength(vMyBuf, 0); 
    end; 
end; 

有一个类似的代码写入数据。

。是否可以直接访问值?无需复制Value字典(vMyBuf:= MyBufs.Items[SeledData];)。

。有没有更好的方法?

回答

2

您最好使用类 的隐式引用语义并使用TObjectDictionary。

type 
    TMyBuf   = class 
     public 
     Data:array[0..(500-1)] of Byte; 
    end; 
    TMyKey   = string[50]; 
    TMyBufs   = TObjectDictionary<TMyKey,TMyBuf>; 
var 
    MyBufs  :TMyBufs; 

这将允许您轻松地在字典中写入单个字节。你当然必须通过调用它的构造函数来分配每个TMyBuf。同样,如果你使用了一个TObjectDictionary,它可以拥有(意味着因此知道如何释放)放入它的所有对象引用,清理起来会更容易。

另一件你可能不知道的事情是在Unicode delphi上,string[50]是一个古老的TurboPascal/DOS时代的shortstring类型,而不是一个unicode字符串。

我建议,除非你真的需要,你不用担心使用字符串[50],只是使用字符串。如果您希望在运行时验证该字符串的长度不超过50个字符并引发异常,请按照这种方式进行。

+0

谢谢,我不需要Unicode。 仍然没有回答第二个问题。 – MohsenB 2013-03-28 14:33:59

+1

这是更好的方法。 – 2013-03-28 21:46:45