Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the effect of having an empty while loop?

I know this might be a bit of a 'silly' question, but sometimes, I just want to loop until a condition is false but I don't like keeping the loop empty. So instead of:

Visible = true;
while(IsRunning)
{
}
Visible = false;

I usually prefer:

while(IsRunning)
{
    Visible = true;
}
Visible = false;

However, I'm a bit concerned about what exactly happens at the line Visible = true;. Does the Runtime keep executing that statement even though it's redundant? Is it even advisable to do it this way? Many 'code-enhancements' plugins don't like empty while loops, and I don't really understand why.

SO:

  • Is there anything wrong with having an empty while loop?

  • Does having a loop such as shown above have any performance effects?

Thanks!

like image 980
Chibueze Opata Avatar asked Dec 26 '22 20:12

Chibueze Opata


1 Answers

This is called busy or spin waiting.

The main problem is, that you are blocking the thread, that is running this while loop. If this thread is GUI thread, then it will result in freezing and unresponsible GUI. And yes, this results in loss of performance, because neither compiler, nor OS can know if they can somehow optimize this while loop.

Just try making single loop like this and see how one core of your CPU is running at 100%.

The right way to do this is to use asynchronous programming, where your code gets notified, either by event or language construct (like await) when the previous operation finished running.

But it is usually used in low-level systems or languages. .NET 4.0 introduces SpinWait construct, that serves as efficient threading sychnronization.

And in relation to your question. I believe neither should be used. They are both problematic for both debugging, performance and clarity of code.

like image 95
Euphoric Avatar answered Jan 12 '23 06:01

Euphoric