2

"Reading an array of bytes at a time is much faster than reading one byte at a time"
I saw the sentence there while i was trying to learn for input stream. Why this is the case?

Ziya ERKOC
  • 811
  • 6
  • 15
  • 1
    This can get into a reaaallly broad discussion. Basically reading in chunks is just faster than reading a single byte, due to computer architecture, electronics, and who knows what else. – Kayaman Jul 10 '17 at 20:11
  • 7
    Which is faster? 1. Pick up a book, read *one letter*, put the book down, repeat. 2. Pick up a book, read a *whole sentence*, put the book down, repeat. – QBrute Jul 10 '17 at 20:18
  • Wow! Thanks for perfect answers – Ziya ERKOC Jul 10 '17 at 20:20
  • 1
    It depends on number of connections you make to file to read bytes from. If you read each byte during one connection then it is as fast as reading all bytes in one connection. – Jay Smith Jul 10 '17 at 20:24
  • Because I/O is slow. – Lew Bloch Jul 10 '17 at 23:18

1 Answers1

5

It's not that obtaining an array of 50 bytes is faster than obtaining 1 byte. It's that over time, it is faster to get 1,000,000,000 bytes of data in chunks of 50 than it is to get 1,000,000,000 bytes one by one.

It's the same reason we don't go to the grocery store for one thing at a time.
It's the trip that takes the most time, not the amount of groceries that we get.
(groceries being bytes in this example, and trip being the retrieval of data from memory)

Kylon Tyner
  • 351
  • 1
  • 12
  • 2
    Thank you for your answer with a nice example :) – Ziya ERKOC Jul 10 '17 at 20:22
  • 1
    It's also worth mentioning that this is highly dependent on the kind of input steam. One based on an in-memory byte array is going to be very fast, even for one byte at a time. One based on a file is going to benefit more from chunking. Taking the analogy, it depends on how far away the groceries are. That's why we buy groceries lot at a time, but are okay grabbing just one bottle out of a fridge, even if we might want a second bottle in a few minutes. – yshavit Jul 10 '17 at 21:04