What is so special about 4kb for buffer length?

When executing the IO file in .NET, it seems that 95% of the examples I see use a 4096 byte buffer. What is so special about 4kb for buffer length? Or is it just a convention similar to using I for an index in a for loop?

+6
source share
4 answers

This is because 4K is the default cluster size for drives up to 16 TB. Therefore, when choosing the size of the buffer, it makes sense to allocate a buffer in several cluster sizes.

A cluster is the smallest distribution unit for a file, so if a file contains only 1 byte, it will consume 4 KB of physical disk space. And the 5K file will result in an 8K distribution.


Update : added code sample to get disk cluster size
using System;
using System.Runtime.InteropServices;

class Program
{
  [DllImport("kernel32", SetLastError=true)]
  [return: MarshalAs(UnmanagedType.Bool)]
  static extern bool GetDiskFreeSpace(
    string rootPathName,
    out int sectorsPerCluster,
    out int bytesPerSector,
    out int numberOfFreeClusters,
    out int totalNumberOfClusters);

  static void Main(string[] args)
  {
    int sectorsPerCluster;
    int bytesPerSector;
    int numberOfFreeClusters;
    int totalNumberOfClusters;

    if (GetDiskFreeSpace("C:\\", 
          out sectorsPerCluster, 
          out bytesPerSector, 
          out numberOfFreeClusters, 
          out totalNumberOfClusters))
    {        
      Console.WriteLine("Cluster size = {0} bytes", 
        sectorsPerCluster * bytesPerSector);
    }
    else
    {
      Console.WriteLine("GetDiskFreeSpace Failed: {0:x}", 
        Marshal.GetLastWin32Error());
    }

    Console.ReadKey();
  }
}
+8
source

Several factors:

  • Most often, 4K is the size of the cluster on disk.
  • 4K is the most common page size on Windows, so the OS can store memory card files in 4K blocks.
  • 4K page can often be transferred from disk to OS to user process without copying
  • Windows caches files in RAM using 4K buffers.

Most importantly, over the years, many of them have used 4K as the length of the buffer because of the above, so a large number of IO and OS code are optimized for 4K buffers!

+1
source

, Windows:. NET.

0

... , - . , , , -, .

(4096, 8192 1024) , . , , . , ( ), . , ( ) . (!) ... - 23 . 1k, 2k, 4k ( ) 8k ( ).

, 8 (-) , . !

The fact that hard disks have this size (cluster) is not the reason for the size of the buffer — the opposite is true — the organization of hard disks follows the above system.

0
source

All Articles