views:

1013

answers:

3

What is the difference between using a BufferedReader around the StringReader in the following code vs using the StringReader only? By loading up the DOM in line 2 of both examples, it seems like the BufferedReader is not necessary?

    InputSource is = new InputSource(new StringReader(html));
    Document dom = XMLResource.load(is).getDocument();

VS

    InputSource is = new InputSource(new BufferedReader(new StringReader(html)));
    Document dom = XMLResource.load(is).getDocument();
+2  A: 

The BufferedReader version was copied from some code that used to read from a FileReader?

Licky Lindsay
+4  A: 

EDIT: My original answer below. The below isn't relevant in this case, since the buffered reader is wrapping a StringReader, which wraps a String. So there's no buffering to be performed, and the BufferedReader appears to be redundant. You could make an argument for using best/consistent practises, but it would be pretty tenuous.

Possibly the result of a copy/paste, or perhaps an IDE-driven refactor too far!

BufferedReader will attempt to read in a more optimal fashion.

That is, it will read larger chunks of data in one go (in a configurable amount), and then make available as required. This will reduce the number of reads from disk (etc.) at the expense of some memory usage.

To quote from the Javadoc:

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders

Brian Agnew
And this is relevant to a StringReader how exactly? ;)
Jon Skeet
Yes. I take your point. I answered that rather too fast :-)
Brian Agnew
+9  A: 

In this particular case, I see no benefit. In general there are two benefits:

  • The oh-so-handy readLine() method is only defined in BufferedReader rather than Reader (irrelevant here)
  • BufferedReader reduces IO where individual calls to the underlying reader are potentially expensive (i.e. fewer chunky calls are faster than lots of little ones) - again, irrelevant for StringReader

Cut and paste fail?

Jon Skeet