Is there a performance impact when calling toList()?
Yes of course. Theoretically even i++
has a performance impact, it slows the program for maybe a few ticks.
What does .ToList
do?
When you invoke .ToList
, the code calls Enumerable.ToList()
which is an extension method that return new List<TSource>(source)
. In the corresponding constructor, under the worst circumstance, it goes through the item container and add them one by one into a new container. So its behavior affects little on performance. It's impossible to be a performance bottle neck of your application.
What's wrong with the code in the question
Directory.GetFiles
goes through the folder and returns all files' names immediately into memory, it has a potential risk that the string[] costs a lot of memory, slowing down everything.
What should be done then
It depends. If you(as well as your business logic) gurantees that the file amount in the folder is always small, the code is acceptable. But it's still suggested to use a lazy version: Directory.EnumerateFiles
in C#4. This is much more like a query, which will not be executed immediately, you can add more query on it like:
Directory.EnumerateFiles(myPath).Any(s => s.Contains("myfile"))
which will stop searching the path as soon as a file whose name contains "myfile" is found. This is obviously has a better performance then .GetFiles
.
List<T>
in favour of aT[]
if it makes the code more logical/readable/maintainable (unless of course the conversion was causing noticeable performance problems in which case I'd re-visit it I guess). – SepsterAdd
orRemove
, I would leave it asIEnumerable<T>
(or even bettervar
) – p.s.w.gEnumerateFiles
instead ofGetFiles
, so only one array will be created. – tukaefGetFiles(directory)
, as it is implemented in .NET currently, pretty much doesnew List<string>(EnumerateFiles(directory)).ToArray()
. SoGetFiles(directory).ToList()
creates a list, creates an array from that, then creates a list again. Like 2kay says, you should be preferring to doEnumerateFiles(directory).ToList()
here. – Joren