Reputation: 12424
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?
Upvotes: 23
Views: 15671
Reputation: 18694
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");
}
Upvotes: 13
Reputation: 21389
Locking no. Slow, depends on what you're comparing it to. It's fairly cheap as far as I/O goes, but I/O is generally slow overall compared to other operations. So, if you must use it, it won't hurt too bad. However, I'd try not to call it more times than is truly necessary! :-)
Upvotes: 8
Reputation: 182
Best would be to run some tests in your environment. I have an app that can do 10,000+ per second without a hiccup to my systems. I consider that pretty fast.
Upvotes: 2
Reputation: 26698
File.Exisits
with kernel32.dll FindFirstFile open handler to the file. If resulting handle is invalid, it return false. If valid it fill data structure with all stuff like LastAccessTime, CreationTime, file size and so on. And then return true. Nothing blocking.
Upvotes: 2
Reputation: 5994
I don't think it is (file operations are heavily optimized and cached on most OS's) and most of the other operations are more likely to be culprits here (sockets, DB access, general processing, etc). But, as usual, the best way is to actually profile your application and see if it's an hotspot.
Upvotes: 7