首页 > 解决方案 > 为什么使用 1024 作为缓冲区?

问题描述

我正在浏览另一位开发人员编写的一些源代码,当涉及到流(文件、内存等)和文件/内容上传时,我遇到了以下代码行。此人使用 1024 作为缓冲区是否有特殊原因?为什么这个 1024 乘以 16?

byte[] buffer = new byte[16*1024];

有人可以进一步澄清这一点吗?此外,如果有人可以指导我阅读文章等以进一步阅读和理解这一点,那就太棒了。

标签: c#.net

解决方案


The practice of allocating memory in powers of 2 is holdover from days of yore. Word sizes are powers of 2 (e.g. fullword = 32 bits, doubleword = 8 bits), and virtual memory page sizes were powers of 2. You wanted your allocated memory to align on convenient boundaries as it made execution more efficient. For instance, once upon a time, loading a word or double word into a register was more expensive in terms of CPU cycles if it wasn't on an appropriate boundary (e.g, memory address divisible by 4 or 8 respectively). And if you were allocating a big chunk of memory, you might as well consume a whole page of virtual memory, because you'd likely lock an entire page anyway.

These day it doesn't really matter, but old practices die hard.

[And unless you knew something about how the memory allocator worked and how many words of overhead were involved in each malloc()'d block... it probably didn't work anyway.


推荐阅读