0

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?

2
  • 1
    this is the kind of micro-optimization you really shouldn't spend time worrying about... Commented Oct 7, 2009 at 19:16
  • Indeed but I see this "psfs" pattern all the time so I wondered if there was any efficiency gain to declaring the query as a "psfs" or inline -- guess not, cheers. Commented Oct 7, 2009 at 19:58

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

So, in other words, if I used B my local string is not interned and would be garbage collected but in C the string SQL will be interned and not be GC'd
no, you did not read the answer correctly. all your snippets result in an interned string.
1

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).

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.