Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » J2EE Interest »

Re: Performance of BufferedOutputStream.write()

Tim Wood

2005-01-07

Replies:

At 10:20 PM 01/06/05, you wrote:
>Frans Verhoef wrote:
>
>> You should try to read from file and output to the net at the same time. ... Memory will saved, as you do not need to keep the whole file in memory, but only the part which you load in buffer.
>
>I totally agree. I was just wondering if someone could venture a guess
>as to how much of a performance hit doing it the current way vs. what
>you suggest is.

Somewhere between huge and mega. Think about it: in one session, read in a 2MB file. You sit doing all that I/O before sending word one to the client. Then at the end, you have that file's contents sitting around in the heap. Unless you re-use it, it becomes garbage, the next session wants to run, eventually you garbage collect, slowing things further, ....

>The reason I ask is that I don't want to fix it (i.e. implement your
>solution) if all I will get is a 5% performance improvement. I'm in need
>of a >2x performance benefit :(

It is trivial to fix. As has been suggested, just run a simple loop when you get the request:
byte[] buf = new byte[64 * 1024];
while (bytes left in input file) {
    read input file block into buf;
    write buf to return stream;
}
close return stream;
You use a single 64K (not M) buffer per download session. Don't bother about caching the file unless its very frequently accessed (the OS will keep some of the file around anyway.) The download is bound by the HTTP connection, not the file I/O.

G'night.
TW



>Jc
>Note: This e-mail contains privileged and confidential information

I promise not to tell another soul. :)

===========================================================================
To unsubscribe, send email to listserv@(protected)
of the message "signoff J2EE-INTEREST". For general help, send email to
listserv@(protected)".
©2008 junlu.com - Jax Systems, LLC, U.S.A.