While programming, I often come across the following scenario (described in code). I define variables in the block that they are going to be used.
int maximumLengthOfToken = 0;
while(fileScanner.hasNextLine())
{
String line; // definition
line = fileScanner.nextLine();
Scanner lineScanner; // definition
lineScanner = new Scanner(line);
String token = lineScanner.next(); // definition and assignment
if(stringToMatch.endsWith(token))
{
if(token.length() >= maximumLengthOfToken )
{
maximumLengthOfToken = token.length();
builder.append(line);
builder.append("\n\n\n");
}
}
}
fileScanner.close();
However, sometimes, for the sake of “neatness” and also because I come from a C background, I like to define all variables at the top, regardless of where they are used. So I do the following –
int maximumLengthOfToken = 0;
String line; // definition
Scanner lineScanner; // definition
String token; // definition
while(fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
lineScanner = new Scanner(line);
token = lineScanner.next(); // definition
if(stringToMatch.endsWith(token))
{
if(token.length() >= maximumLengthOfToken )
{
maximumLengthOfToken = token.length();
builder.append(line);
builder.append("\n\n\n");
}
}
}
fileScanner.close();
“Ah! It looks so neat”, I think.
However, does this have any effect on the performance of the code? Would the first style lead to faster executing code or the second style? Also, what is the convention in such cases? I believe it is the first style.
No. There will be no performance difference.
If you doubt this, ask yourself, “Will it take longer for the computer to look up my variable if it’s 2000 bytes away, than it will if it’s 200 bytes or 20 bytes away?” The answer should be no.
The only case where it might make a difference is if your variable drops out of the processor cache (see locality) before it gets used, in which case moving the variable closer to where it is being used might improve speed. But it would take a lot of code between the variable and its use for that to happen.
It is also possible that the compiler will compile your method down to the same bytecode anyway. In short, I think you don’t have to worry about it.