简体   繁体   中英

On the longevity of static strings vs seemingly local strings in Java

Given the following snippet A

private static final String SQL = "SELECT * FROM TABLE WHERE ID = ?";

and snippet B

public List<MyObject> getData(final Long id){
    return (List<MyObject>)template.query("SELECT * FROM TABLE WHERE ID = ?",id);
}

and snippet C

public List<MyObject> getData(final Long id){
    return (List<MyObject>)template.query(SQL,id);
}

Are B and C effectively the same? Does my string in B get gc'd (young generation?) because it has local scope?

String constants are always interned . Every time you call snippet B it will use the same string object. Basically it's equivalent to snippet A+C.

Indeed, two string constants which have the same sequence of characters will use references to the same string too:

String x = "a" + "b";
String y = "ab";

System.out.println(x == y); // true

No. Neither B nor C create a String . The String will be created when the code is loaded (if it does not already exist as an interned String ). It will be garbage collected along with the rest of the code (unless there is another reference to the same String instance).

Both B and C use the same string value, since all strings are essentially "cached" by the JVM. They exist in memory as long as they need to.

Whether to use B or C is a matter of code readability (and maintainability). Approach B offers the advantage that the SQL query string is immediately adjacent to the code that uses its results, so there should be no question as to what the query is at the point it's being used.

Approach C is advantageous if you're using the same SQL query string in many places, allowing you to define the string once for the whole class (or package, even). If you ever have to change it everywhere it's used, you only need to change that one definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM