Search code examples
javastringperformancememorystring-pool

Java - Regarding performance and memory use, why it's better to use a string into a static field instead of declaring it every time it's needed?


Why it's better to use a string into a static field instead of declaring it every time it's needed?

// Old scenario
Person p = new Person("Charles", "Xavier");
Person p = new Person("Charles", "Doe");
Person p = new Person("Charles", "Johnson");

// New scenario
private static String name = "Charles"

Person p = new Person(name, "Xavier");
Person p = new Person(name, "Doe");
Person p = new Person(name, "Johnson");

I have like a good practice to replace the same String like "Charles" with a static field, but regarding memory use and performance, is it better?


Solution

  • In terms of JVM is concerned, both are same and both go to the String pool.

    However, from a code quality perspective, it's better to define as a constant so that you have a single point to look and change if you have to do that later.