Question

I've got a question about speeding up the loading of a text file. There may be a similar thread already, but it's pretty hard to find.

I've got an interesting set-up. On launch the app contacts my server for the latest data. This is basically a long text file containing some app info as well as the latest data. This works quite well. There is a service with an ASyncTask that does this. I've included the code for the task below.

I've enabled some caching on the server and the file loads pretty quick in my browser. However, it takes longer (like 30+ seconds) from my app, even on great connections. I've enabled GZIP on my server, and that makes loading in the browser even quicker (<1 second). However, my app is still slow. Considering this happens on the first start-up of the app it's quite a bad experience to have to wait this long.

Are there any more things I can do to speed up this process from the app?

Thanks in advance

(Code below)

    private class DownloadData extends AsyncTask<String, Void, String> { 

          @Override
          protected String doInBackground(String... params) { 
              String result = ""; 
              try { 
                // Create a URL for the desired page 
                URL url = new URL("LINK HERE"); 

                // Read all the text returned by the server 
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
                String str;  
                while ((str = in.readLine()) != null) { 
                    result += str; 
                } 
                in.close(); 
            } catch (MalformedURLException e) { 
            } catch (IOException e) { 
            } 
              return result; 
          }       

          @Override
          protected void onPostExecute(String result) { 
            // Result processed here. It takes 30 seconds to reach this point, so no delay is happening here
          } 

          @Override
          protected void onPreExecute() { 
             // Some UI Things
          } 

          @Override
          protected void onProgressUpdate(Void... values) { 
          } 
    } 
Was it helpful?

Solution

I am not sure that it it is the biggest problem in your code but you can try to optimize by not using a string class but char[].

 char[] resultTab=new char[Integer.MAX_VALUE];
 int i=0;
 while ((resultTab[i] = in.read()) != -1) { 
          i++;
 } 
 String result = String.copyValueOf(resultTab, 0, i);

In place of Integer.MAX_VALUE, you put the lenght estimate of your string. (a bit more, if your not sure let it)

If you are using a string your aplication have to alocate new memory when your text became bigger, with a char [], it will alocate memory only once.

Tell me if it's work, i am interest by the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top