最快读取文件长度C#的方式
问题说明
我使用 fs.Length
,其中 FS
是的FileStream
。
这是一个 O(1)
操作?我认为这会从文件的属性只读取,而不是去通过文件找到时,寻求位置已经到达终点。该文件我想找到的长度可以很容易地从1 MB到GB 4-5。
Is this an O(1)
operation? I would think this would just read from the properties of the file, as opposed to going through the file to find when the seek position has reached the end. The file I am trying to find the length of could easily range from 1 MB to 4-5 GB.
不过,我注意到,有一个的FileInfo
类,它也有一个长度
属性。
However I noticed that there is a FileInfo
class, which also has a Length
property.
执行这两个长度
性能理论上需要的时间是相同的?抑或是 fs.Length
慢,因为它必须先打开的FileStream?
Do both of these Length
properties theoretically take the same amount of time? Or does is fs.Length
slower because it must open the FileStream
first?
正确答案
自然的方式来获得的文件大小 .NET 是你提到的 FileInfo.Length 属性。
The natural way to get the file size in .NET is the FileInfo.Length property you mentioned.
我不知道 Stream.Length
较慢(它不会读取整个文件无论如何),但它肯定更自然的使用的FileInfo
,而不是的FileStream
,如果你不打算读取该文件。
I am not sure Stream.Length
is slower (it won't read the whole file anyway), but it's definitely more natural to use FileInfo
instead of a FileStream
if you do not plan to read the file.
下面是一个小的基准,它会提供一些数值:
Here's a small benchmark that will provide some numeric values:
private static void Main(string[] args)
{
string filePath = ...; // Path to 2.5 GB file here
Stopwatch z1 = new Stopwatch();
Stopwatch z2 = new Stopwatch();
int count = 10000;
z1.Start();
for (int i = 0; i < count; i )
{
long length;
using (Stream stream = new FileStream(filePath, FileMode.Open))
{
length = stream.Length;
}
}
z1.Stop();
z2.Start();
for (int i = 0; i < count; i )
{
long length = new FileInfo(filePath).Length;
}
z2.Stop();
Console.WriteLine(string.Format("Stream: {0}", z1.ElapsedMilliseconds));
Console.WriteLine(string.Format("FileInfo: {0}", z2.ElapsedMilliseconds));
Console.ReadKey();
}
结果
Stream: 886
FileInfo: 727
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhbigigc
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20