JavaAntiPatterns

Collection of bad coding practices

Unbuffered I/O

with 2 comments

Reading and writing I/O streams byte-by-byte is too expensive, as every read()/write() call refers to the underlying native (JNI) I/O subsystem. Usage of buffered streams reduces the number of native calls and improves I/O performance considerably.

Bad:

InputStream in = new FileInputStream(f); 
int b; 
while ((b = in.read()) != -1) {    
    ... 
}   

Good:

InputStream in = new BufferedInputStream(new FileInputStream(f));
...
Advertisements

Written by Alex

November 22, 2007 at 2:41 pm

Posted in I/O

Tagged with

2 Responses

Subscribe to comments with RSS.

  1. How about:

    byte[] buffer = new byte[4096];
    int length = in.read(buffer);
    while(length > 0) {
    out.write(buffer, 0, length);
    length = in.read(buffer);
    }

    …thats how I transfer bytes from stream to stream…

    regards, Andy

    BTW: nice blog, keep up the good work

    Andy

    September 5, 2008 at 6:36 am

  2. i have read that BufferedInputStream has synchronized modifier, so it can be slower than InputStream that hasn’t have this modifier (but we can see that it has native instead), some dirty tests can approve this theory, but I have tested and noticed, that BufferedInputStream is faster even if we try to read single char in file.

    yury

    December 25, 2011 at 12:24 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: