Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Could you explain to me which code is better (more optimal) and why?

Vesion 1:

while(something){
Runnable task = (Runnable) taskQueue.dequeue();
Throwable  ex = null;
...
}

Version 2:

Runnable task;
Throwable ex;

while(something){
task = (Runnable) taskQueue.dequeue();
ex = null;
...
}

For me it looks like second version is optimized because variable declaration is out of while loop.

share|improve this question
6  
Any compiler worth its salt would move the declaration out for you automatically. Use the second if task and ex are to be accessed outside the block. Otherwise no recommendation here. –  rahul May 26 '12 at 21:06

2 Answers 2

up vote 3 down vote accepted

At the bytecode level, there is no such thing as inner block. All local variables are declared at the scope of the method. As a result, both your variants should produce equivalent bytecode. To make sure, decompile them with javap and look at the bytecode. From the programmer's point of view, version 1 is more clear and concise.

share|improve this answer

The first code style is more preferred according to concept "minimization of life variables" (R. Martin "Clean code"). In byte-code there is no diff.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.