string memory allocation

后端 未结 4 1633
[愿得一人]
[愿得一人] 2021-01-22 14:49

which one is better

System.out.println(\"hello world\");

or

String s=\"hello world\";
System.out.println(s);
相关标签:
4条回答
  • 2021-01-22 15:37

    There is no difference in terms of memory allocation for this simple example.

    0 讨论(0)
  • 2021-01-22 15:37

    There is no difference in this case.

    It's important to realize how references works, and that local variables are distinct from the objects they are referring to. The memory required by local variables themselves are insignificant; you should never hesitate from declaring local variables if it makes the code more readable.

    Consider for example the following code:

    String s1 = "a very long string...";
    String s2 = s1;
    

    This code declares two String references, but they both refer to the same String object. The memory requirement is not doubled in cases like this.

    You should never underestimate how smart the compiler can be at optimizing codes. Consider the following for example:

    System.out.println("Hello world!");
    System.out.println("Hello world!");
    System.out.println("Hello world!");
    

    The above snippet in fact does NOT store the string object "Hello world!" three times in memory! The literal is interned and only stored once in memory.

    References

    JLS 3.10.5 String Literals

    Each string literal is a reference to an instance of class String. String objects have a constant value. String literals --or, more generally, strings that are the values of constant expressions-- are "interned" so as to share unique instances, using the method String.intern.

    Related questions

    • what is the advantage of string object as compared to string literal
      • On "string" vs new String("string")
    • Is it good practice to use java.lang.String.intern()?
    • Java: Why doesn’t my string comparison work?
    • Java String.equals versus ==
    0 讨论(0)
  • 2021-01-22 15:37

    Check out JLS to understand how strings are treated internally by JVM.

    0 讨论(0)
  • 2021-01-22 15:47

    No difference.

    But, if you were to compare

    String s=new String("hello world");
    System.out.println(s);
    

    with

    System.out.println("hello world");
    

    Then there would be a potential difference, as the latter case would be a candidate for string internalisation, wheras the former would not.

    0 讨论(0)
提交回复
热议问题