简体   繁体   中英

Efficiency of Code: Java Transfer File over TCP

I would like to know the difference in terms of performance between these two blocks that try to send a big file over a TCP socket. I couldn't find much resources explaining their efficiency.

A-

byte[] buffer = new byte[1024];
int number;

while ((number = fileInputStream.read(buffer)) != -1) {
socketOutputStream.write(buffer, 0, number);
}

B-

byte mybytearray = new byte[filesize];
os.write(mybytearray);

Which one is better in terms of transfer delay?

Also What is the difference if i set the size to 1024 or 65536? How would that affect the performance.

The latency until the last byte of the file arrives is basically identical. However the first one is preferable, although with a much larger buffer, for the following reasons:

  1. The data starts arriving sooner.
  2. There is no assumption that the file size fits into an int .
  3. There is no assumption that the entire file fits into memory, so
  4. It scales to very large files without code changes.

Your MTU (Maximum Transmission Unit) size is likely to be around 1500 bytes. This means your data will be broken up (or combined into) this size no matter what you do. Any reasonable buffer size from 512 byte up is likely to give you the same transfer speed.

How you send and receieve data impact the amount of CPU you use. Unles syou have a fast network eg 10 GB, your CPU will mroe than keep up with your network.

Writing the code in an efficient manner will ensure you don't waste CPU (which is a good thing) but shouldn't make much difference to your transfer speed which is limited by your bandwidth (and latency of your network)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM