从高效地输入流的Android阅读 [英] Android Reading from an Input stream efficiently
问题描述
我想提出一个HTTP GET请求发送到网站上的Android应用程序,我做。
I am making an HTTP get request to a website for an android application I am making.
我使用的是DefaultHttpClient并使用HTTPGET发出请求。我得到的实体响应,并从此获得一个InputStream对象获取页面的HTML。
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.
这是低效率的?我不是装大的网页 - www.cokezone.co.uk 这样的文件大小并不大。有没有更好的方式来做到这一点?
Is this inefficient? I'm not loading a big web page - www.cokezone.co.uk so the file size is not big. Is there a better way to do this?
感谢
刘德华
推荐答案
在code中的问题是,它是创造大量的重字符串
对象,复制所有它的内容,并与他们做业务。为了彻底改善它,你应该使用的StringBuilder
,即避免实例化新的字符串
物体上的每个追加,它直接使用没有内部字符数组复制它们。在实现你的情况会是这样的:
The problem in your code is that it's creating lots of heavy String
objects, copying all its contents and doing operations with them. To drastically improve it you should use StringBuilder
, that avoid to instantiate new String
objects on each append, it directly uses the internal char arrays without copy them. The implementation for your case would be something like that:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
之后,你可以使用总
为的CharSequence
为很多情况下无需将其转换为字符串
。如果你需要做到这一点,使用 total.toString()
的循环之后。
After that you can use total
as a CharSequence
for lots of cases without convert it to String
. If you need to do it, use total.toString()
after the loop.
我会尽力解释它更好的......
I'll try to explain it better...
-
A + = B
(或A = A + B
),是A
和B
字符串,副本A
和B
字符到一个新的对象(注意,您还复制A
,包含的不小累积字符串
),和你正在做的每一次迭代这些副本。复制一些Kbs的,并创造了一些对象,很多时候是昂贵的。 -
a.append(B)
,是A
A的StringBuilder
,直接追加B
内容A
,这样你就不会复制在每次迭代累积字符串。
a += b
(ora = a + b
), beinga
andb
Strings, copiesa
andb
chars to a new object (note that you are also copyinga
, that contains the not-small accumulatedString
), and you are doing those copies on each iteration. Copying some Kbs and creating some objects lots of times is expensive.a.append(b)
, beinga
aStringBuilder
, directly appendsb
contents toa
, so you don't copy the accumulated String on each iteration.
这篇关于从高效地输入流的Android阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!