Is there any benefit to returning the result of assigning a value to a local variable rather than the value directly?

前端 未结 6 1124
死守一世寂寞
死守一世寂寞 2021-01-17 09:01

I am doing a java code inspection. Here is a function (snippet):

String getValue() {
     String res;
     StringBuilder strBuilder = new StringBuilder();

         


        
6条回答
  •  孤城傲影
    2021-01-17 09:28

    You cant do either

    String res = strBuilder.toString();
    return res ;
    

    Or directly,

    return strBuilder.toString();
    

    Now If you want to know about benefits as you asked Is there any benefit, i always prefer directly return. My personal logic is simple as

    • You gonna write one line less code !!! (declaring variables allover is not a good feeling to me and also you don't have to think about the name of the variable, conflicts etc.. those silly matter )
    • The value will not be stored in memory and wait for the GC to collect it. SO, less memory see.....
    • Fast write to a variable and then read from it and return ..... more read/write isn't it?

    Those things are nothing big, I had to say as you asked

提交回复
热议问题