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

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

问题描述

我正在写一个表演必不可少的服务,我不知道最快的是什么。我有几个对象(50-200),每个对象都有一个ID(例如84397或23845)。是否有更快的字典,KeyValue对的列表或列表,索引设置为ID,其余的具有空值或具有相同想法的数组?

解决方案

这取决于要执行的操作。我们假设你想要找到一个给定的ID 的对象。




  • / em>方法是最快的:访问 myArray [84397] 是一个常量时间操作 O(1)。当然,这种方法需要最多的记忆。

  • 字典几乎一样快,但需要较少的内存,因为它使用哈希表内部。

  • 方法的列表是最慢的,因为您可能必须遍历整个列表以找到您的条目,这样才能生成 O(n) 复杂度



因此,在你的情况下,我会选择字典,除非大数组的性能稍微好一些在你的情况下真的很相关。


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?

解决方案

It depends on which operation you want to execute. Let's assume that you want to find an object with a given ID.

  • 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天全站免登陆