In a class for handling SQL transactions in Java, I'm find myself using the classes PreparedStatement and ResultSet all the time.
I got curious to know what would be better (more efficient) practice in Java; declaring them as members of the class ...
class SqlThingy {
PreparedStatement pstx;
ResultSet rs;
public void SqlThingyMethod() {
pstx = database.connection.prepareStatement("...");
....
}
}
... or as local variables of individual methods?
class SqlThingy {
public void SqlThingyMethod() {
PreparedStatement pstx;
ResultSet rs;
pstx = database.connection.prepareStatement("...");
}
}
Does the VM merely overwrite the contents of the class member with the (reference to the) new preparedstatement, or will it do some additional initialization that also claims resources and even out the difference of allocating local variables every time?
Be sure to distinguish between variables and the objects they point to. As a general principle, do not reuse variables to point to different objects. This is extremely error prone.
In your specific example, since you are recreating the connection object in each call to SqlThingyMethod there is likely no benefit to storing it in a field. Use a local variable.
Variables are cheap. Objects are, if not exactly expensive, less cheap. In this case, the object may actually be expensive, but the variable is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With