I have got a little question about buffer size in Java. Why do we set buffer size to 1024 or 2^n. For example:
inputStream = file.getInputStream();
File newFile = new File("C:/uploads/operators.xml");
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
How outputStream.write(bytes, 0, read); works? Why do we use bytes array?
To avoid wasting hit to file system, byte sizes should be a multiple of file system sector size (e.g. 512 bytes).
Same applies to CPU L1 cache.
Most Intel 486 CPUs has 1K L1 cache, thus the value 1024.
Pentium CPUs have at least 8K L1 cache, thus 8 * 1024 is also often used.
Recent file systems have a sector size of 4K and recent CPUs have at least 64K L1 Cache, thus 64 * 1024 is also a choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With