skwear skwear - 1 year ago 74
C# Question

Would AddRange() be faster than ToList() in this case?

I have a comma delimited string called

which I want to split and put into a

Would using LINQ,

List<string> f = ctext.Split(',').ToList();

be slower than not using LINQ?

List<string> f;

It seems that LINQ would actually copy something somewhere at some point which would make it slower, whereas
would just check the size of the list once, expand it, and dump it in.

Or is there an even faster way? (Like using a
loop, but I doubt it.)

Answer Source

Fortunately, we can easily look at what ToList does now that it's open source. (Follow the link for the latest source...)

I haven't seen IListProvider<T> before, but I doubt that an array implements it, which means we've basically got new List<TSource>(source). Looking at the List<T> source shows that both the constructor and AddRange basically end up using CopyTo.

In other words, other than a few levels of indirection, I'd expect them both to do the same thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download