Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient it is to return a string in Java

All sample function I've seen so far avoid, for some reason, returning a string. I am a total rookie as far as Java goes, so I am not sure whether this is intentional. I know that in C++ for example, returning a reference to a string is way more efficient than returning a copy of that string.

How does this work in Java?

I am particularly interested in Java for Android, in which resources are more limited than desktop/server environment.

To help this question be more focused, I am providing a code snippet in which I am interested in returning (to the caller) the string page:

public class TestHttpGet {
    private static final String TAG = "TestHttpGet";

    public void executeHttpGet() throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI("http://www.google.com/"));
        HttpResponse response = client.execute(request);    // actual HTTP request

        // read entire response into a string object
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String page = sb.toString();
        Log.v(TAG, page); // instead of System.out.println(page);
        }
    // a 'finally' clause will always be executed, no matter how the program leaves the try clause
    // (whether by falling through the bottom, executing a return, break, or continue, or throwing an exception).
    finally { 
            if (in != null) {
                try {
                    in.close();     // BufferedReader must be closed, also closes underlying HTTP connection
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In the example above, can I just define:

    public String executeHttpGet() throws Exception {

instead of:

    public void executeHttpGet() throws Exception {

and return:

        return (page); // Log.v(TAG, page);
like image 572
Regex Rookie Avatar asked Mar 22 '26 18:03

Regex Rookie


1 Answers

A String in java corresponds more or less to std::string const * in c++. So, it's cheap to pass around, and can't be modified after it's created (String is immutable).

like image 136
Erik Avatar answered Mar 24 '26 08:03

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!