2

I am using jdbc and I am storing SQL Queries in a interface or class and having all of them as public static and final. Say:

public static final QUERY_1="insert into table1 (c11,c12) values (?,?)";

public static final QUERY_1="insert into table2 (c21,c22) values (?,?)";

observing above two string i thought that insert ,into ,(,), values all these things appear in both the statements.so instead of having them in both the string I will have them as constants and create queries by String manipulation on runtime but I am worried whether I will hamper the performance.

What is the suggested approach ?

2
  • How many of these do you have? Commented Nov 25, 2015 at 10:25
  • 3
    This code is as simple and readable as it could be, doesn't create any garbage, and is as fast as it can be. There's no need at all to "optimize" this, just to try saving a tiny bit of memory. Commented Nov 25, 2015 at 10:31

2 Answers 2

2

Don't do it.

public static final QUERY_1="insert into table1 (c11,c12) values (?,?)"; is a compile time constant (comes as part of byte-code). A new String will be created after replacing ?s with actual arguments and then it will be executed. Seems like premature optimization to use insert and into strings separately.

Sign up to request clarification or add additional context in comments.

2 Comments

Most JDBC drivers do not create a new string with the ? replaced with values (I only know that the MySQL JDBC driver does this by default), some drivers might replace the placeholders with implementation specific placeholders (eg PostgreSQL). Most drivers prepare the query with the placeholders, and send the parameter values separately on execute.
@MarkRotteveel - Ya. I just saw that PostgresSQL does what you mentioned - passing parameters values separately. That actually means that using static final String is actually quite efficient. Thank You for your comment on JDBC driver behaviour :)
1

What if you try a intermediate solution? Instead of keeping separate queries as constant, create query at runtime but only once, and then cache it. From second time onward use the same pre generated query.

To do so you can create a QueryGeneratorFactory class which will give you query based on your value. This will create each query for the first time,and keep the query in cache, keyed with the value you pass.

Next time when you call the generator with the same value, it will return the query from cache.

3 Comments

thought the same ,but i still needs the manipulation for one time
Concatenating of non-constant Strings happens at Runtime. This will actually slow down things and make code less readable :)
thought of implementing hibernate like solution

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.