English 中文(简体)
一个有效的Delphi缓存
原标题:An efficient cache in Delphi

我正在 Delphi 2007 中创建一个缓存,它将包含记录。

每条记录包含一个字符串,两个日期和一个值。

Type MyRecord = Record
    Location : String;
    Date1 : TDateTime;
    Date2 : TDateTime;
    Value : Double;
End;

海滩的最大面积没有保障。

It is highly likely that Location will have several entries for different dates
There are only 13 locations.

高速缓存需要可搜索,并且位于性能关键的位置。

I was thinking of creating a 2 dimensional array for this structure with a sorted string list as an index. So when search I d access the Stringlist to look up the index I need in the array with name value pairs. (Location = Index) Then I d need loop through the items for each location to see if the value is in the cache matching both Date1 and Date2. If the value isn t in the cache I need to go and get it from a database and add it to the cache.

某种类似的东西

Type MyRecord = Record
    Date1 : TDateTime;
    Date2 : TDateTime;
    Value : Double;
End;
...
Cache: Array[1..13] of Array of MyRecord
Locations: TStringList;

由于地点将列于示意图清单。

这个结构适用于缓存吗?

最佳回答

您的结构足以用于缓存,但我不会在性能关键位置使用它。如果您的缓存增长,并且有5000个项目在一个位置上,您仍然需要通过5000个项目进行线性搜索。

我认为最好对您的列表进行排序并使用二分搜索在缓存中搜索项目。

如果我要实现这样的东西,我会使用一个指向记录的 TList。然后我会使用 TList.Sort 进行排序,给它一个根据记录包含的数据排序的过程。排序将在具有最大选择性的字段上进行,然后在具有第二大选择性的字段上进行,以此类推。

如果您想找到一个条目,您可以在列表上进行二进制搜索并获取值,如果不存在,您可以从数据库中获取它并添加到缓存中。

当然,这一切都将被优美地封装在一个类中,该类将负责这些问题并处理内存分配问题。

一个哈希映射也是可能的,但是你需要进行测试以确定哪个更快。

问题回答

你的想法听起来很合理,应该可以有效地运行。本质上,您将实现一个带有索引的简单数据库表。它将索引信息与数据分开,使得更新索引的成本相对于在排序结构中移动数据而言“较小”。

另一个可能性是使用内存数据库。Delphi有许多这样的数据库可供选择。它们能为你完成很多工作,可能还能提供更大的灵活性。

如果性能是一个问题,尽量避免字符串比较。相反,我会将缓存数组按照所需的搜索顺序进行排序,并对原始数据执行二进制搜索。

如果字符串值最重要,则使用类似于soundex算法的东西将字符串分成单个字符和数字,并将两者编码为一个单词或整数(简单哈希)。按照此方式对数组进行排序,并在任何冲突时按位置字符串排序。这样,您不会执行针对明显的非匹配的字符串匹配。





相关问题
determining the character set to use

my delphi 2009 app has a basic translation system that uses GNUGetText. i had used some win API calls to prepare the fonts. i thought it was working correctly until recently when someone from Malta ...

Help with strange Delphi 5 IDE problems

Ok, I m going nuts here. For the last (almost) four years, I ve been putting up with some extremely bad behavior from my Delphi 5 IDE. Problems include: Seemingly random errors in coride50.bpl ...

How to write a Remote DataModule to run on a linux server?

i would like to know if there are any solution to do this. Does anyone? The big picture: I want to access data over the web, using my delphi thin clients. But i´would like to keep my server/service ...

How convert string to integer in Oxygene

In Delphi, there is a function StrToInt() that converts a string to an integer value; there is also IntToStr(), which does the reverse. These functions doesn t appear to be part of Oxygene, and I can ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签