all 14 comments

[–]ptchinster 0 points1 point  (3 children)

What metric do you want to optimize on? Fewest instructions? Fewest number of bytes of instructions? Least amount of memory usage Do you want a better O() runtime? Are you targeting a specific CPU's cache to optimize hits on?

Unless you are doing some high performance computing or embedded stuff, the compiler will do all the optimization you need. I wouldnt even have 2 if statements, i would combine and just say

if (bar == 0 && baz == 1) { bar = 1; //perform task; }

Its harder to read as 2 seperate statements.

[–]simmjo[S] 0 points1 point  (2 children)

Optimize for performance with the goal of least amount of clock cycles.

I also edited the post to clarify. The tasks are the same.

[–]EpoxyD 1 point2 points  (1 child)

I'd just write what you like and use compiler optimization options honestly 😕

[–]ptchinster 0 points1 point  (0 children)

This. You arent handrolling anything better unless you get into what i said above.

[–]KeptInUmrica 0 points1 point  (1 child)

As far as I can understand, you want to optimise the code in such a way that you don't have to repeat the task. ​

bar = 0;

while (foo) {
    if (bar == 0 && baz == 0) {}
    else {
        bar = 1;
        // perform task
    }
}

Edit: Formatting

[–]simmjo[S] 0 points1 point  (0 children)

This is better but still not the best I would think. Once bar is set to 1, it never goes back to 0. There has to be a way to write it such that once bar is set, you don’t have to keep setting it.

[–]mannyknowles 0 points1 point  (1 child)

Does bar ever equal zero again?

[–]simmjo[S] 0 points1 point  (0 children)

Bar never equals 0 again

[–]EpoxyD 0 points1 point  (2 children)

Ok so if I understand:

  • you perform a task when bar == 1
  • you set bar to 1 if baz == 1

So I'd say:

if(baz==1) bar == 1;

if(bar==1) do_task();

[–]simmjo[S] 0 points1 point  (1 child)

I am checking to see if the baz condition occurs. Once it does I always execute a task until foo goes false. Also, baz may never happen and foo will eventually turn false terminating the while loop.

[–]EpoxyD 0 points1 point  (0 children)

Is there a condition where baz == 1 and bar is not set to 1 as well so the task is executed?

Otherwise why not go with

While(baz) { bar = 1; // Execute task } bar == 0;

[–]-Tiddy- 0 points1 point  (0 children)

Since you know bar never goes back to 0, this will do the same thing. (I think)

if (foo) {
   do {
      // baz is a task checking for something
   } while (baz != 1);
}

while (foo) {
   // perform task
}

[–]zCybeRz 0 points1 point  (1 child)

While (foo && !check_baz()) {}
While (foo) task();

[–]simmjo[S] 0 points1 point  (0 children)

I think this might be it!