Re: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
Does anyone know if this is a particularly slow or locking operation which could impact server performance in a large environment?
In computing, there is actually no such thing as an "expensive operation", unless you consider what it is expensive in relation to.
For instance, in the real world, would $2.000.000 for an object be expensive? What if it is the price of Bahamas? Would it be expensive then? What about for a carton of milk? Is that expensive?
The thing you need to consider is if File.Exists
is expensive in terms of the overall operation you intend to do, and whether or not you actually have any alternatives.
If you don't have any alternatives, does it matter if it is expensive or not?
For instance, if you do 1 check if the file exists, and then if it does, you load it in, and spend an hour processing it, then I would assume it would not be considered expensive.
However, if you call it 10 times in a single loop, to figure out if a file exists, and then if it does, just increment a number, then it might be the most expensive single operation you do there.
The only way you can know for sure is to actually measure how long that method call takes, compared to what else you in the same operation.
In year 2016 it doesn't seem to be very expensive and there also seem to be no real difference between File.Exists
and PathFileExists
(Why is File.Exists() much slower when the file does not exist?). The only difference I could measure is that it's faster to check for a non-existing file then an existing one:
(Tested on an SSD)
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
private extern static bool PathFileExists(StringBuilder path);
void Main()
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
File.Exists(@"c:\Home\Temp\test_.log");
}
sw.Stop();
sw.Dump("File.Exists = false");
sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
File.Exists(@"c:\Home\Temp\test.log");
}
sw.Stop();
sw.Dump("File.Exists = true");
var sb = new StringBuilder(@"c:\Home\Temp\test_.log");
sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
PathFileExists(sb);
}
sw.Stop();
sw.Dump("PathFileExists = false");
sb = new StringBuilder(@"c:\Home\Temp\test.log");
sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
PathFileExists(sb);
}
sw.Stop();
sw.Dump("PathFileExists = true");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With