Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization for: while (true)

I'm using a

while (true)
{
    if (x == y)
    {
        break;
    }
    else
    {
        //do stuff
    }
}

loop like so, the frame is just an example frame, as the actual code itself is convoluted and overly complicated that it requires a "break;" statement in multiple different areas for multiple different conditions. My question is; Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?

edit: (java)

edit2:

while (a < b)
{
    while (true)
    {
        if (c < d)
        {
            if (e == null)
            {
                //do alot of stuff
                break;
            }
            else
            {
                //do something
            }
        }
        else if (d > c)
        {
            if (e == null)
            {
                //do alot of stuff
                break;
            }
            else
            {
                //do something
            }
        }
        else if (d == c)
        {
            break;
        }
    }
    a = a + 1;
}
like image 999
Sam Thompson Avatar asked Nov 07 '22 13:11

Sam Thompson


1 Answers

Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?

You can write an infinite loop in multiple ways, but they are all equivalent. Neither is really more efficient than the others:

  1. while (true) { ... }
  2. do { ... } while (true);
  3. for (;;) { ... }

Depending on the actual code, it may make sense to reverse the "break-loop-logic" into "continue-loop-logic", as in:

boolean continueLoop;
do {
    continueLoop = false;

    // ... do stuff ...

    if ( some condition ) {
        continueLoop = true;
    }

    // ... do stuff ...

} while (continueLoop);
like image 68
Alex Shesterov Avatar answered Nov 12 '22 18:11

Alex Shesterov