2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 6
    \$\begingroup\$ 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. \$\endgroup\$ May 26, 2012 at 21:06

2 Answers 2

3
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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