0

Possible Duplicate:
Is it better to call ToList() or ToArray() in LINQ queries?

Hi,

I have following code

static void Main(string[] args)
        {
            const string FileName = @"c:\words";
            HashSet<string> wordLookup = new HashSet<string>(File.ReadAllLines(FileName), StringComparer.InvariantCultureIgnoreCase);
            List<string> wordList1 = wordLookup.ToList();
            string[] wordList2 = wordLookup.ToArray();
        }

Could any one please tell which one is faster

List<string> wordList1 = wordLookup.ToList();

or

string[] wordList2 = wordLookup.ToArray();
Community
  • 1
  • 1
manu
  • 1,807
  • 4
  • 25
  • 32
  • 1
    And you don't care about how fast and how easy item lookups, copying/cloning, inserting/removing items, etc. are in teach? – Platinum Azure Apr 18 '11 at 15:56
  • 2
    Write a loop and use StopWatch class. – Jakub Konecki Apr 18 '11 at 15:56
  • 2
    All I can do is sigh. And both of those lines of code work faster than I can sigh. – BoltClock Apr 18 '11 at 15:56
  • 2
    have you considered benchmarking the performance of each call yourself using a timer? – Brian Driscoll Apr 18 '11 at 15:56
  • I'd bet that if you've got a large enough set where the difference between the two matter, it will be the HashSet that becomes the bottleneck. – ceyko Apr 18 '11 at 15:57
  • @Forgotten Semicolon, I will be using this in a Parallel Link Query. However in that context both will support because both of them are implementing IEnumerable interface. Hence though the performance difference is trivial I would like to know which one is the best for the usage in LINQ. – manu Apr 18 '11 at 16:00

2 Answers2

1

List<T> uses array internally, so my guess is that they'll be equally fast. However, this just doesn't matter -- use whatever makes your code clearer.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
0

My initial reaction would be to say that ToArray would be faster, but honestly the only way to tell is to time it yourself.

Barry
  • 2,053
  • 3
  • 17
  • 28
  • 2
    My initial reaction would be the opposite. In both cases an array will be repeatedly reallocated (length whenever full) as the source is enumerated. In the case of ToList, the reallocated array will be internal to the List, and the resulting List can be returned as-is. In the case of ToArray, there is typically an additional step needed to copy the resulting data to an array of the right length. – Joe Apr 18 '11 at 16:42