Efficient input stream for string method in java

So, I ran the profiler on my (albeit fairly simple) Java application and was surprised that the second only for methods that required making HTTP requests in terms of time is my inputStreamToString method. It is currently defined as follows:

 public static String inputStreamToString(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } in.close(); return sb.toString(); } 

How can I do it faster? (And yes, I really need strings, and no, InputStrings are not that big, and no, this method is called less often than most methods in the program, and no, I can’t avoid the need for conversion.)

+4
source share
3 answers

It’s good that where all the I / O operations take place (I assume that the profiler turns on readLine () all the time to wait for data input). The only obvious thing you could do is to initialize the StringBuilder with a sufficiently large buffer, so it does not need to reallocate the memory, but I suppose that it is distorted all the time in the time taken to read the data.

Other than that, you are associated with I / O. It just takes time to receive data over the network.

EDIT: May also include a comment on casablanca: instead of reading in turn and then adding a new line, you can use a simple reader with a reasonably large buffer that you provide and just block everything. There is no need to read line by line, since you just copy all the input anyway. The only argument for manually switching one by one is if you want to normalize newline characters (for example, \r\n ) to the standard \n .

+5
source

Try using IOUtils.copy () from jakarta commons. Create a ByteArrayOutputStream, copy the bytes from the HTTPRequest stream into this ByteArray, then create a line using a new line (bytes, "UTF-8").

I believe it could be faster ...

But your code looks like it was written to illustrate good style and good coding. I really don't understand what could be ineffective here. It probably takes time because the rest of your logic is relatively simple and well written? I mean, probably, although this piece of code takes a relatively long time, is it not too critical?

0
source

Check it out [link text] [1] There are many suggestions.

[1]: fooobar.com/questions/226 / ...

0
source

All Articles