Dylan Wheeler
Dylan Wheeler

Reputation: 7074

Java - The Most Efficient Way to Load Text From Website?

I have a question for you all. I am going for speed, and I need to use this method a lot, so the more efficient this method is, the better.

My code:

private void method(final String name) {
    final URL url = new URL("http://www.somewebsite.com/blah.php?name=" + name);
    final BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
    final String totalText = in.readLine();
    in.close();
    //other stuff using the totalText variable
}

This method works, but I am asking if there is a more efficient way for this to work.

Important Notes Concerning the code I am reading:

Upvotes: 2

Views: 697

Answers (1)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. If its one line of code, as you have changed you question then do the following... Use Only InputStream and Scanner.

final URL url = new URL("http://www.somewebsite.com/blah.php?name=" + name);
InputStream i = url.openStream();
Scanner scan = new Scanner(i);
final String totalText = scan.nextLine();

2. If mulitple lines then, I will advice you not to create a String object every time, cause creating Object on the Heap is expensive.

These 2 below lines will create a lot of String object on the heap.

((inputLine = in.readLine()) != null)

totalText += inputLine;

Use StringBuilder which is Mutable, and at the end assign it to the String reference using toString() method.

Eg:

StringBuilder totalText;
   String ftotal;

   while ((inputLine = in.readLine()) != null) {
    totalText.append(inputLine);
}


   ftotal = totalText.toString();

Upvotes: 2

Related Questions