This may be tedious, but I would love to know which is a more efficient way of programming. The result may only be slightly better or slightly worse, but I am still interested in which is 'better'.
Say I want to create an array of String
objects based on the amount of columns I received from an SQL query and then go ahead and fill this String[]
object with values through the use of a for
loop. i.e.
if(rs.next()) {
String[] topLine = new String[metadata.getColumnCount()];
for (int i = 0; i < metadata.getColumnCount(); i++) {
topLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);
}
writeNext(topLine);
}
See the use of metadata.getColumnCount()
to fetch the amount of columns, only twice. Would it be more appropriate (and faster) to bring this value into it's own variable such that:
int columnCount = metadata.getColumnCount();
and make use of it only twice? Or should I leave the method to call twice?
What n
times do I have to call metadata.getColumnCount()
before it becomes more efficient to use a local variable. Is there even any change?
Edit: By the way, this isn't my code, I picked it up as an example.
2 Answers 2
When should I instantiate a variable rather than grabbing it through a method?
When the value returned in the method has meaning or will be use past the name of the method, then get the value and assign it to variable with the appropriate name.
If metadata.getColumnCount()
is constant during the loop, then you can get it and cache it in a local before the loop.
Either way I wouldn't be concerned about the performance of the get
unless you have been able to measure the degradation and it would make a difference to the application. Focus on the clarity and the intent of the code, optimise based on performance measurements. Modern compilers and VM are very good at what they do.
It depends on the intent of your code and avoiding repeating yourself.
If the intent is to rely on the return value of a method to be the same in both instances, assign a single variable. This way, another developer does not have to determine whether or not both uses of the method will always return the same value.
In this example, every developer should know your intent is to apply the same value twice:
thisCount = metadata.getColumnCount()
DoSomething(thisCount)
DoSomethingElse(thisCount)
Now, if there is a new parameter to apply to that method, you only need to change in one place:
thisCount = metadata.getColumnCount(skipPrimaryKey = true)
N = 1
.