字典,列表或数组? [英] Dictionary, List or Array?

查看:235
本文介绍了字典,列表或数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个服务,而性能是必不可少的,我不知道什么是最快的东西。我有几个对象(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.

这篇关于字典,列表或数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆