Hashan JXT
Hashan JXT

Reputation: 41

Why Use 1024 for a buffer?

I was going through some source code written by another developer and I came across the following line of code when it comes to streams (file, memory, etc) and file/content uploads. Is there a particular reason that this person is using 1024 as a buffer? Why is this 1024 multiplied by 16?

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

Could someone please clarify this further? Also, it would be awesome if anyone can direct me towards articles, etc to further read and understand this.

Upvotes: 2

Views: 7877

Answers (2)

Jesse
Jesse

Reputation: 1425

1024 is the exact amount of bytes in a kilobyte. All that line means is that they are creating a buffer of 16 KB. That's really all there is to it. If you want to go down the route of why there are 1024 bytes in a kilobyte and why it's a good idea to use that in programming, this would be a good place to start. Here would also be a good place to look. Although it's talking about disk space, it's the same general idea.

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74317

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.

Upvotes: 4

Related Questions