I have been playing around with the BlockingCollection class, and I was wondering why the ToArray() Method is an O(n) operation. Coming from a Java background, the ArrayList’s ToArray() method runs in O(1), because it just returns the internal array it uses (elementData). So why in the world do they iterate through all of the items, and create a new Array in the IEnumerable.ToArray method, when they could just override it and return the internal array the collection uses?
I have been playing around with the BlockingCollection class, and I was wondering why
Share
No, it really doesn’t. It creates a copy of the array. From the docs for
ArrayList.toArray:So basically, the premise of your question is flawed in the Java sense.
Now, beyond that,
Enumerable.ToArray(the extension method onIEnumerable<T>) in general would be O(N), as there’s no guarantee that the sequence is even backed by an array. When it’s backed by anIList<T>, it usesIList<T>.CopyToto make things more efficient, but this is an implementation-specific detail and still doesn’t transform it into an O(1) operation.