简体   繁体   English

快速静态键值映射

[英]fast static key-value mapping

I have a set of unique key-value pairs, both key and value are strings. 我有一组唯一的键值对,键和值都是字符串。 The number of pairs is very huge and finding the value of a certain string is extremely time-critical. 对的数量非常大,找到某个字符串的值非常关键。

The pairs are computed beforehand and are given for a certain program. 这些对是预先计算的,并针对特定程序给出。 So i could just write a method containing: 所以我可以写一个包含以下内容的方法:

public String getValue(String key)
{
    //repeat for every pair
    if(key.equals("abc"))
    {
        return "def";
    }
}

but i am talking about more than 250,000 pairs and perhaps sorting them could be faster... 但我说的是超过250,000对,也许对它们进行排序可能会更快...

I am having a class that contains the getValue() method and can use its constructor, but has no connection to any database/file system etc. So every pair has to be defined inside the class. 我有一个包含getValue()方法的类,可以使用其构造函数,但与任何数据库/文件系统等都没有连接。因此,每一对都必须在该类内定义。

Do you have any ideas that could be faster than a huge series of if-statements? 您有没有比一系列if语句更快的想法? Perhaps using a sorting map that gets the pairs presorted. 也许使用排序图对将这些对进行预排序。 Perhaps improve constructor-time by deserializing an already created map? 也许通过反序列化已创建的映射来改善构造器时间?

I would like your answers to contain a basic code example of your approach, I will comment answers with their corresponding time it took an a set of pairs! 我希望您的答案包含您的方法的基本代码示例,我将对答案和它们花了一对时间的相应时间进行注释!

Time-frame: for one constructor call and 20 calls of getValue() 1000 milliseconds. 时间范围:一个构造函数调用和20个getValue()调用1000毫秒。

Keys have a size of 256 and values have a size < 16 键的大小为256,值的大小为<16

This is exactly what a hash table is made for. 这正是哈希表的用途。 It provides O(1) lookup if implemented correctly, which means that as long as you have enough memory and your hash function and collision strategy are smart, it can get values for keys in constant time. 如果实施正确,它将提供O(1)查找,这意味着,只要您有足够的内存并且哈希函数和冲突策略很聪明,它就可以在恒定时间内获取键的值。 Java has multiple hash-backed data structures, from the sounds of things a HashMap<String, String> would do the trick for you. Java具有多个哈希支持的数据结构,从HashMap<String, String>可以为您解决问题。

You can construct it like this: 您可以这样构造它:

 Map<String, String> myHashTable = new HashMap<String, String>();

add values like this: 添加这样的值:

 myHashTable.put("abcd","value corresponding to abcd");

and get the value for a key like this: 并获得像这样的键的值:

myHashTable.get("abcd");

You were on the right track when you had the intuition that running through all of the keys and checking was not efficient, that would be an O(n) runtime approach, since you'd have to run through all n elements. 当您直觉认为通过所有键运行和检查效率不高时,您将走在正确的轨道上,这将是O(n)运行时方法,因为您必须运行所有n元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM