在Java中返回字符串的效率如何

Reg*_*kie 2 java performance

到目前为止,我见过的所有样本函数都会因某种原因避免返回一个字符串.就Java来说,我是一个新秀,所以我不确定这是否是故意的.我知道在C++中,返回对字符串的引用比返回该字符串的副本更有效.

这在Java中如何工作?

我对Java for Android特别感兴趣,其资源比桌面/服务器环境更有限.

为了帮助这个问题更集中,我提供了一个代码片段,我有兴趣返回(给调用者)字符串页面:

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();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我可以定义:

    public String executeHttpGet() throws Exception {
Run Code Online (Sandbox Code Playgroud)

代替:

    public void executeHttpGet() throws Exception {
Run Code Online (Sandbox Code Playgroud)

并返回:

        return (page); // Log.v(TAG, page);
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 15

java中的String或多或少与std::string const *c ++ 相对应.因此,传递它很便宜,并且在创建后不能修改(String是不可变的).


Jon*_*eet 13

String是一个引用类型 - 所以当你返回一个字符串时,你真的只是返回一个引用.这很便宜.它不是复制字符串的内容.

  • 它更接近于c ++指针而不是c ++引用,因为它可以为null.在java术语中,引用是正确的词. (2认同)

Kon*_*rus 5

在java中大多数时候你返回的东西,你通过引用返回它.没有任何对象复制或克隆.所以它很快.

此外,Java中的字符串是不可变的.也不用担心.