0

As the title says is which one of the scenarios below is faster?

        // Using FileInfo
        FileInfo file = new FileInfo(@"C:\Test.txt");

        if (file.Exists)
            file.CopyTo(@"C:\TestCopy.txt");

        // Using File
        if (File.Exists(@"C:\Test.txt"))
            File.Copy(@"C:\Test.txt", @"C:\TestCopy.txt");

I know the FileInfo is easier for the eye to read, but is one method faster than the other?

Dumpen
  • 1,622
  • 6
  • 22
  • 36
  • Have you tried to write a benchmark for your case? – Dustin Kingen Jun 03 '13 at 12:18
  • write small test and share the result – Mzf Jun 03 '13 at 12:18
  • 4
    see: http://stackoverflow.com/questions/1324788/what-is-the-difference-between-file-and-fileinfo-in-c . YMMV, and will depend on your exact use case, so doing a benchmark as suggested by others is probably the best way to find out. – Jan Thomä Jun 03 '13 at 12:19
  • 3
    If I were to _guess_ I'd say the first one is marginally faster. It's likely that the _exact_ same API operations are being performed internally, but in the second case one of them is being performed twice. – David Jun 03 '13 at 12:20
  • 2
    You won't be able to tell them apart. Use whichever you like best. – Matthew Watson Jun 03 '13 at 12:22

1 Answers1

3

Difference is that FileInfo cache information: file existing check is executed once. Then, if you check Exists property and THEN create file, new call to Exists property always will return false.

stefano m
  • 4,094
  • 5
  • 28
  • 27
  • This is true, but note that the file existance check is lazily executed. – Matthew Watson Jun 03 '13 at 12:44
  • @MatthewWatson How so? Further explanation would be appreciated! – SepehrM May 14 '14 at 19:09
  • 1
    @SepehrM I mean that an internal bool field for `FileInfo.Exists` isn't initialised by the `FileInfo` constructor. Instead, it is initialised when you first call `FileInfo.Exists`. (You can see this by inspecting the implementation using Reflector or similar.) – Matthew Watson May 15 '14 at 07:45
  • @MatthewWatson Thanks, I wasn't familiar with the term "Lazy Evaluation/Execution"! – SepehrM May 15 '14 at 10:48