简体   繁体   中英

Python vs C# dictionaries

I've been coding in Python for a while now and I got used to thinking that dictionaries have worst case O(n) time complexity ( source ). However, at work I have to use C# and I've just recently find out that dictionaries in C# have much better time complexity ( source ). Why is that? What advantages do python dictionaries have over C# ones?

By the way, which implementation is more common? If I ever have to use dictionaries from another language's standard library what time complexity will they most probably have?

Thanks!

MSDN documentation speaks about average case time complexity (more particularly, they say that the complexity "approaches" the given function), and these are the same as presented in Python documentation. Python additionally provides worst case complexities. For some operations MSDN also provides worst case estimations (example: http://msdn.microsoft.com/en-us/library/k7z0zy8k%28v=vs.110%29.aspx ).

It does not make sense to compare average case with worst case.

Skipping the theory, in practice: average case describes what you should expect in general when performing an operation. Worst case informs you that sometimes, in some particular conditions and/or for some particular data, the operation may perform slower.

Also, it's best to focus on one particular operation. Discussing "complexity of a dictionary" in general also doesn't make much sense.

I assume that dictionaries in Python and C# use much the same implementation: a hashed lookup.

The time order of a hashed lookup is slightly great than O(1). On average, once the key has been hashed, it can be found in one access or slightly longer (for hash collisions).

The worst case performance of a hashed lookup is O(n). If all the keys in the dictionary have the same hash value then the search becomes (usually) equivalent to linear brute force.

So yes, Python has worst case O(n) and C# has average time complexity of O(1+). On the other hand, Python has average time complexity of O(1+) and C# has worst case of O(n).

In other words, they're the same (to a first order approximate). And so are all the others you're likely to run into.

But watch out for anything that is a sorted dictionary. They're very different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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