问题描述
当我构造一个新的 BufferedReader
时,它为我提供了8192个字符的缓冲区。这背后的逻辑/原因是什么?
When I construct a new BufferedReader
it is providing me a buffer of 8192 characters. What is the logic/reason behind this?
8192 = 2 to the power of 13
推荐答案
传统上,操作系统中的内存管理器和页面文件可以在大小为2.这允许通过左/右移位运算执行非常有效的乘法/除法运算。使用缓冲区时,最坏的情况是缓冲区的大小比页面大小长1个字节(这将导致额外的页面交换,但收益非常低)。因此,默认的缓冲区大小也将倾向于以两个为因数来实现。
Traditionally, memory managers and paging files in the operating system work on pages that are sized in powers of 2. This allows very efficient multiply/divide operations to be performed with left/right shift operations. When working with a buffer, the worst case scenario is to have a buffer with size 1 byte longer than the page size (that would result in an extra page swap with very low benefit). So the default buffer sizes will also tend to be implemented in factors of two.
我假设(但尚未检查)JVM寻找这样的缓冲区,并且尝试在页面边界上对齐它们。
I'd assume (but have not checked) that the JVM looks for buffers like this and attempts to align them on page boundaries.
为什么这很重要?页面遗失非常昂贵。如果您要处理大量IO,则最好避免将支持缓冲区的页面换出到磁盘上(这会破坏缓冲区的用途)。也就是说,对于大多数应用程序来说,这是一个微优化,在大多数情况下,默认设置都可以。
Why does this matter? Page misses are quite expensive. If you are doing a ton of IO, it's better to avoid the case where the page backing the buffer gets swapped out to disk (kind of defeats the purpose of the buffer). That said, for most applications, this is a micro-optimization, and for the vast majority of cases, the default is fine.
作为参考,Windows和Linux当前都使用4KB的内存页面大小。因此,BufferedReader上的默认缓冲区将恰好占用2页。
For reference, Windows and Linux both currently use a 4KB memory page size. So the default buffer on BufferedReader will consume exactly 2 pages.
这篇关于为什么默认的char缓冲区大小为BufferedReader 8192?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!