0

Does this makes a difference in memory consumption/performance?

private static final String name = "text";

    // new string is created and passed in new Test-Object
public Test create1(){
    return new Test("text");
}

    // static final string passed (as reference?) in new Test-Object
public Test create2(){
    return new Test(name);
}

Imagine having 100000 objects, then for create1, a string is created every time. create2 does not create a new string every time. Am I right?

pvg
  • 2,673
  • 4
  • 17
  • 31
nimo23
  • 5,170
  • 10
  • 46
  • 75
  • you're missing the point. of course they will create new ones, since you call the new keyword. but the name variable itself will only exist once if it's static, or, for each instance, if it's not static. – Stultuske Oct 05 '17 at 12:49
  • 7
    I think even for `create1` the strings should get "pooled", but I'm not certain about the details... basically, you could test by picking any two random `Test` instances and comparing their respective strings with `==` to see whether those are the same instance. – tobias_k Oct 05 '17 at 12:50
  • 3
    Related information for String Pool: https://stackoverflow.com/a/3052456/6073886 – OH GOD SPIDERS Oct 05 '17 at 12:52
  • yes, I mean the name variable itself is NOT created 10000 times with create2()-method. This is what I want, no waste of memory. – nimo23 Oct 05 '17 at 12:53
  • 4
    Both methods do the ___exact___ same thing anyway. `name` is a compile time constant and will be inlined by the the compiler. – Tom Oct 05 '17 at 12:54
  • 1
    Actually, if I remember, the byte code would be the same. a `static final` will be replace by its value during the compilation, so in create2, you end up with `"text"` too. (if I remember correctly). – AxelH Oct 05 '17 at 12:55
  • Waste of memory where? What is the implementation of `Test`? As shown, there is no obvious difference in the memory usage from the two calls. What do you think is 'using more memory'? – pvg Oct 05 '17 at 12:56
  • I have thougth with create1() a new String is created with every new Object. However, as it explained here, this is not the case. Both, create1 and create2 does exactly the same thing with the string-value. – nimo23 Oct 05 '17 at 12:57

1 Answers1

0

I have thougth with create1() a new String is created with every new Object. However, as it explained above in the comment section, this is not the case.

Both methods, create1() and create2() does on runtime exactly the same thing with the string-value.

nimo23
  • 5,170
  • 10
  • 46
  • 75