I am making an HTTP get request to a website for an android application I am making.
I am using a DefaultHttpClient and using HttpGet to issue the request. I get the entity response and from this obtain an InputStream object for getting the html of the page.
I then cycle through the reply doing as follows:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String x = "";
x = r.readLine();
String total = "";
while(x!= null){
total += x;
x = r.readLine();
}
However this is horrendously slow.
Is this inefficient? I’m not loading a big web page – http://www.cokezone.co.uk so the file size is not big. Is there a better way to do this?
Thanks
Andy
The problem in your code is that it’s creating lots of heavy
Stringobjects, copying their contents and performing operations on them. Instead, you should useStringBuilderto avoid creating newStringobjects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:You can now use
totalwithout converting it toString, but if you need the result as aString, simply add:String result = total.toString();
I’ll try to explain it better…
a += b(ora = a + b), whereaandbare Strings, copies the contents of bothaandbto a new object (note that you are also copyinga, which contains the accumulatedString), and you are doing those copies on each iteration.a.append(b), whereais aStringBuilder, directly appendsbcontents toa, so you don’t copy the accumulated string at each iteration.