Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

c# - Linq ToList/ToArray/ToDictionary performance

Well I encounter many situations where having an IEnumerable is not enough. However I'm unsure about the performance of the above method calls.

What I really want to ask is:

Is the performance of ToList/ToArray:

  1. an O(n) operation which copies the IEnumerable to a new array/List ?
  2. If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ?

  3. Some magic happens and the performance is O(1)?

Probably to Dictionary is O(n), right ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is the performance of ToList/ToArray an O(n) operation which copies the IEnumerable to a new array/List ?

Yes. ToList is slightly more efficient, as it doesn't need to trim the internal buffer to the right length first.

If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ?

No. For both calls, a new collection is always created; that's a shallow copy of the original collection. It's more efficient to call ToList or ToArray on any ICollection<T> than on a simple IEnumerable<T> which doesn't implement ICollection<T> though, as with a collection the length is known to start with. (This is detected at execution time though; you don't need to worry about the compile-time type.)

Probably to Dictionary is O(n), right ?

Assuming the hash is sensible, it's O(N), yes. Basically it creates a new dictionary in exactly the way you'd probably expect it to.

You might want to read the corresponding posts in my Edulinq blog series:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...