Use multiple return statement - optimization

Is there a considerable difference of optimization between these two codes (in Java and/or C++, currently, even if I guess it's the same in every languages) ? Or is it just a question of code readability ?
int foo(...) {
if (cond) {
if (otherCondA)
return 1;
if (otherCondB)
return 2;
return 3;
}
int temp = /* context and/or param-dependent */;
if (otherCondA)
return 4 * temp;
if (otherCondB)
return 4 / temp;
return 4 % temp;
}
and
int foo(...) {
int value = 0;
if (cond) {
if (otherCondA)
value = 1;
else if (otherCondB)
value = 2;
else value = 3;
}
else {
int temp = /* context and/or param-dependent */;
if (otherCondA)
value = 4 * temp;
else if (otherCondB)
value = 4 / temp;
else
value = 4 % temp;
}
return value;
}
The first one is shorter, avoid multiple imbrications of else statement and economize one variable (or at least seems to do so), but I'm not sure that it really changes something...

After looking deeper into the different assembly codes generated by GCC, here's the results :
The multiple return statement is more efficient during "normal" compilation, but with the -O_ flag, the balance change :
The more you optimise the code, the less the first approach worths. It makes the code harder to optimise, so, use it carefully. As said in comments, it's very powerful when used at the front of the function when testing preconditions, but in the middle of the function, it's a nightmare for the compiler.

Of course the multiple return is acceptable.
Because you can halt the program as soon as the function is finished

Related

Creating single use intermediate variables

I've read somewhere that a variable should be entered into the code if it is reused. But when I write my code for logic transparency, I sometimes create intermediate variables (with names reflecting what they contain) which are used only once.
How incorrect is this concept?
PS:
I want to do it right.
It is important to note that most of the time clarity takes precedence over re-usability or brevity. This is one of the basic principles of clean code. Most modern compilers optimize code anyway so creating new variables need not be a concern at all.
It is perfectly fine to create a new variable if it would add clarity to your code. Make sure to give it a meaningful name. Consider the following function:
public static boolean isLeapYear(final int yyyy) {
if ((yyyy % 4) != 0) {
return false;
}
else if ((yyyy % 400) == 0) {
return true;
}
else if ((yyyy % 100) == 0) {
return false;
}
else {
return true;
}
}
Even though the boolean expressions are used only once, they may confuse the reader of the code. We can rewrite it as follows
public static boolean isLeapYear(int year) {
boolean fourth = year % 4 == 0;
boolean hundredth = year % 100 == 0;
boolean fourHundredth = year % 400 == 0;
return fourth && (!hundredth || fourHundredth);
}
These boolean variables add much more clarity to the code.
This example is from the Clean Code book by Robert C. Martin.

understanding a piece of code with ``boolean`` and ``switch``

i was looking some examples of interactions with the keyboard and stumbled upon this code that i found interesting. But i'm having trouble understanding a certain part of it(it's marked down below).I don't get how all this whole ''boolean'' declaration, ''switch'' and ''CASE'' works, i tried to look in the reference but still. Could someone explain in a simple maner how these work?
float x = 300;
float y = 300;
float speed = 5;
boolean isLeft, isRight, isUp, isDown;
int i = 0;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {// <<<--- From this part down
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
Questions like these are best answered by the reference:
Works like an if else structure, but switch() is more convenient when you need to select between three or more alternatives. Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by a break. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.
The rest of the code is setting the corresponding variable to whatever value you passed in as the b parameter, and then returning it.
You should get into the habit of debugging your code. Add print statements to figure out exactly what the code is doing.

how much time will fibonacci series will take to compute?

i have created the recursive call tree by applying brute force technique but when i give this algorithm 100 values it takes trillion of years to compute..
what you guys suggest me to do that it runs fast by giving 100 values
here is what i have done so far
function fib(n) {
if (n =< 1) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
You can do it also with a loop:
int a = 1;
int b = 1;
for(int i = 2; i < 100; i++){
int temp = a + b;
a = b;
b = temp;
}
System.out.println("Fib 100 is: "+b);
The runtime is linear and avoids the overhead caused by the recursive calls.
EDIT: Please note that the result is wrong. Since Fib(100) is bigger than Integer.MAX_VALUE you have to use BigInteger or similar to get the correct output but the "logic" will stay the same.
You could have a "cache", where you save already computed Fibonacci numbers. Every time you try to compute
fib(n-1) /* or */ fib(n-2) ;
You would first look into your array of already computed numbers. If it's there, you save a whole lot of time.
So every time you do compute a fibonacci number, save it into your array or list, at the corresponding index.
function fib(n)
{
if (n =< 1)
{
return n;
}
if(fiboList[n] != defaultValue)
{
return fiboList[n];
}
else
{
int fibo = fib(n-1) + fib(n-2);
fiboList[n] = fibo;
return fibo;
}
}
You can also do it by dynamic programming:
def fibo(n):
dp = [0,1] + ([0]*n)
def dpfib(n):
return dp[n-1] + dp[n-2]
for i in range(2,n+2):
dp[i] = dpfib(i)
return dp[n]

get the number of parents that equal to the sum of children

i have a problem with the below code. i need to get the number of parents that it's value = to the sum of it's 2 children. example if parent value = 10 and its children are 2 and 8.
then i have to count this parent as 1. i need to check for all nodes in the tree.
this is what i tried to do: could you please advise:
int BinaryTree::numberOfSum (){
return numberOfSumImpl (root);
}
int BinaryTree::numberOfSumImpl (BTNode *rootNode, int el){
if(rootNode ==0) return 0;
int count=0;
if(rootNode->hasTwoChildren() || rootNode->isLeaf())
else if{
if (rootNode->info==el) return count=1;
return count + numberOfSumImpl(el,rootNode->left) + numberOfSumImpl(el,rootNode->right);
}
}
Many Thanks,
There seem to be a few problems with the call to numberOfSumImpl, as in the main function it is only called with one parameter, and in the recursive function it is called with two parameters, but with the order inversed. This code does not even compile!
Besides, the condition rootNode->hasTwoChildren() || rootNode->isLeaf()) looks strange and, having its body empty even more strange.
You did not post the definition of the BTNode, but looks like you are looking for something as
int BinaryTree::numberOfSumImpl (BTNode* p) {
if (not p) return 0;
int count;
if (p->hasTwoChildren() and p->info == p->left->info + p->right->info) {
count = 1;
} else {
count = 0;
}
return count + numberOfSumImpl(p->left) + numberOfSumImpl(p->right);
}
And this function would possibly be static.

.Net Parallel.For strange behavior

I brute-forced summing of all primes under 2000000. After that, just for fun I tried to parallel my for, but I was a little bit surprised when I saw that Parallel.For gives me an incorrect sum!
Here's my code : (C#)
static class Problem
{
public static long Solution()
{
long sum = 0;
//Correct result is 142913828922
//Parallel.For(2, 2000000, i =>
// {
// if (IsPrime(i)) sum += i;
// });
for (int i = 2; i < 2000000; i++)
{
if (IsPrime(i)) sum += i;
}
return sum;
}
private static bool IsPrime(int value)
{
for (int i = 2; i <= (int)Math.Sqrt(value); i++)
{
if (value % i == 0) return false;
}
return true;
}
}
I know that brute-force is pretty bad solution here but that is not a question about that. I think I've made some very stupid mistake, but I just can't locate it. So, for is calculating correctly, but Parallel.For is not.
You are accessing the variable sum from multiple threads without locking it, so it is possible that the read / write operations become overlapped.
Adding a lock will correct the result (but you will be effectively serializing the computation, losing the benefit you were aiming for).
You should instead calculate a subtotal on each thread and add the sub-totals at the end. See the article How to: Write a Parallel.For Loop That Has Thread-Local Variables on MSDN for more details.
long total = 0;
// Use type parameter to make subtotal a long, not an int
Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(x) => Interlocked.Add(ref total, x)
);
Many thanks to all of you for your quick answers
i changed
sum += i;
to
Interlocked.Add(ref sum,i);
and now it works great.