开发者

String operations hang on android?

I'm writing an android app that requires that I retrieve the html code of a webpage and get and return specific elements. For some reason, the code seems to hang or take an unbeli开发者_如何转开发evably long time doing basic string operations.

    URL url = new URL(link);
    URLConnection urlConnection = url.openConnection();
    InputStreamReader i = new InputStreamReader(
            urlConnection.getInputStream());
    BufferedReader in = new BufferedReader(i);
    String check = "";
    String html = "";
    while((check = in.readLine()) != null)
        html += check;

Takes minutes to complete on both the emulator and the device with university connection speeds. Whereas

    URL url = new URL(link);
    URLConnection urlConnection = url.openConnection();
    InputStreamReader i = new InputStreamReader(
            urlConnection.getInputStream());
    BufferedReader in = new BufferedReader(i);
    String check = "";
    String html = "";
    int p = 0;
    while((check = in.readLine()) != null)
        p++;

takes ~ 5 seconds and returns the correct number of lines in the html page. Why do the string operations take so long? Just for perspective, the page is about 4000 lines long.


Because you're doing it wrong. Use StringBuilder to build large Strings.

StringBuilder sb = new StringBuilder();
while((check = in.readLine()) != null)
    sb.append(check);
html = sb.toString();

Why StringBuilder when there is String?

String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜