Is there a way to get the size of a file in .NET using a static method?
I know the normal way of getting the size of a file would be to use a FileInfo instance:
using System.IO;
class SizeGetter
{
public static long GetFileSize(string filename)
{
FileInfo fi = new FileInfo(filename);
return fi.Length;
}
}
Is there a way to do the same thing without having to create an i开发者_开发百科nstance of FileInfo, using a static method?
Maybe I'm trying to be overly stingy with creating a new instance every time I want a file size, but take for example trying to calculate the total size of a directory containing 5000+ files. As optimized as the GC may be, shouldn't there be a way to do this without having to tax it unnecessarily?
Don't worry about it. First, allocation in .NET is cheap. Second, that object will be in gen 0 so it should be collected without much overhead.
Don't worry about it.
I've found a blog post of someone who measured the overhead of object creation in .NET (C# Object Creation Time Trials), and, as it turns out, creating 10,000 objects took 0.03 seconds, i.e., 3 µs per object. The time required to read the file length from the file system will surely dominate those 3 microseconds significantly.
A lot of static methods in the .NET framework internally create objects and call instance methods on them (you can verify this by looking at the reference source or by using some reflection tool). You assume that a static method is faster. Do not make such assumptions. If you have two ways to do the same thing, measure which one is faster.
If you really, really need a static method, use the native GetFileSize
or GetFileSizeEx
API. But keep in mind this will require a handle to the file from the CreateFile
API.
You can also view the source of the FileInfo
class:
http://referencesource.microsoft.com/#mscorlib/system/io/fileinfo.cs#4ee673c1a4ecad41
精彩评论