从高效地输入流的Andr​​oid阅读 [英] Android Reading from an Input stream efficiently

查看:116
本文介绍了从高效地输入流的Andr​​oid阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个HTTP GET请求发送到网站上的Andr​​oid应用程序,我做。

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 (or a = a + b), being a and b Strings, copies a and b chars to a new object (note that you are also copying a, that contains the not-small accumulated String), and you are doing those copies on each iteration. Copying some Kbs and creating some objects lots of times is expensive.
  • a.append(b), being a a StringBuilder, directly appends b contents to a, so you don't copy the accumulated String on each iteration.

这篇关于从高效地输入流的Andr​​oid阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆