Is it better if I do this:
foreach my $item ( @array ) {
if ( $bool ) {
.. code ..
}
else {
.. code ..
}
}
or
if ( $bool ) {
foreach my $item ( @array ) {
}
}
else {
foreach my $item ( @array ) {
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I would leave premature optimization aside.
You should go for maintainability first and foremost. Group them in the way that makes more sense taking into account the logical structure of the code (such as grouping related statements together).
If you later determine that performance is an issue, try measuring with something like a profiler to see where the bottlenecks are. Chances are, it’s not there. From Code Complete 2:
We shouldn’t try to guess where to optimize before it is necessary since most of us are really bad at guessing where that slow portion of our code is. Programmers who optimize as they go also spend about 96% of their time optimizing code that doesn’t need to be optimized. Another thing to take into account is that code tuning (as in this example) considers a tradeoff between readability and maintainability for performance:
I’m not saying don’t optimize, but optimize code only in the end, when you have the luxury of the big picture and tools to point you in the right direction.
EXTRA: To answer the question of performance itself, though:
Check this other question here on SO. And this from the first edition of Code Complete.