C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We test whether this is accurate and efficient. We look at an example of using Length on FileStream. And then we benchmark the property.
Note: FileStream has a Length property that returns the byte count. This property is not cached in memory. It is an IO operation.
Example. FileStream has a Length property that will return the length of a file in bytes. This is bytes, not chars, meaning some Unicode strings will have different lengths. The example writes the length of a text file using the Length property.
C# program that uses Length of FileStream using System; using System.IO; class Program { static void Main() { // Open existing text file with File.OpenRead using (FileStream fileStream = File.OpenRead("TextFile1.txt")) { // Use Length property to get number of bytes long length = fileStream.Length; // Write length to console Console.WriteLine("Length: {0}", length); } } }
This example opens the FileStream using the return value of File.OpenRead, a convenient method that works the same as "new FileStream()" with certain parameters. The using-statement ensures correct destruction of the system resources.
Note: Using can solve nasty bugs regarding unavailable disk resources. The using statement is compiled similarly to try-finally.
Inside the using-statement, the example accesses the Length property. This property is slow to access, about equivalent in speed to an actual Read. The length of the file is written to the Console.
Note: In my tests, the size of a 35-byte file was correctly written by the program.
Benchmark. In the C# language, properties like Length are conventionally thought to be fast to access. However, the Length property on FileStream is slow and takes as long as an actual Read or ReadByte.
Here: Accessing Length in addition to a Read doubles the time required. This indicates that Length is accessing the disk each time.
FileStream loop that uses Length: C# using (FileStream fs = File.OpenRead("Program.cs")) { for (int i = 0; i < m; i++) { long len = fs.Length; fs.ReadByte(); } } FileStream loop that avoids Length: C# using (FileStream fs = File.OpenRead("Program.cs")) { for (int i = 0; i < m; i++) { fs.ReadByte(); } } Benchmark results 100000 iterations were tested. FileStream Length used: 413 ms [faster] FileStream alone: 230 ms
Summary. We saw the basics of using Length on streams, and validated our code by checking the file in the file manager. Finally, we saw that using Length on FileStream is about as slow as doing a Read.
Tip: For optimal performance, you should eliminate Length checks when not required, which will decrease the disk accesses.