字典,列表或数组?
我正在写一个服务,而性能是必不可少的,我不知道什么是最快的东西。我有几个对象(50-200),每个中都有一个ID(整数,例如84397或23845)。难道是快有一个字典,键值对的列表,或设置为具有空值或具有相同想法的阵列?
I'm writing a service where performance is essential, and I'm not sure what is the fastest thing. I have a few Objects (50-200) which each have an ID in them (ints, e.g. 84397 or 23845). Would it be faster to have a Dictionary, a List of KeyValue Pairs or a List with the indexes set to the IDs with the rest having null values or an array with the same idea?
这取决于你想要执行该操作。让我们假设你想为找对象给定ID
It depends on which operation you want to execute. Let's assume that you want to find an object with a given ID.
- 的巨大的数组的办法是最快的:访问
myArray的[84397]
是一个固定时间操作的 O(1)。当然,这种方法需要的内存。 - 的字典的几乎一样快,但需要较少的内存,因为它采用的是哈希表内部。
- 的对列表的方法是最慢的,因为你可能不得不遍历整个列表,找到你的记录,这将产生的 O(N)的复杂性。
- The huge array approach is fastest: Accessing
myArray[84397]
is a constant-time operation O(1). Of course, this approach requires the most memory. - The dictionary is almost as fast but requires less memory, since it uses a hash table internally.
- The list of pairs approach is the slowest, since you might have to traverse the whole list to find your entry, which yields O(n) complexity.
因此,在你的情况,我会选择字典,除非巨大的数组的稍微好表现你的情况真的很重要。
Thus, in your situation, I would choose the dictionary, unless the marginally better performance of the huge array is really relevant in your case.