[SOLVED] If Statement Vs. while loop

Issue

I readied some where that while loops are faster than if Statement;

Doesn’t That Make

while(something)
{
    //the code
    break;
}

faster and better than a normal If Statement ??!

If true why people uses the if statements ’till now <– I had to use a while loop right there : )

Thanks.

Solution

It is generally not faster in natively compiled languages like C, C++, Rust, etc. since the optimizing compilers can rewrite this anyway but basic one may not (resulting in more branches. It is bug prone due to the break and does not make the intent clear resulting in a less readable code. Put it shortly: do not use this code to emulate conditions. Instead, write clean codes, check that the compiler does its optimizing job correctly, and only then, use micro-optimization to speed up your code if your profiler show this is needed and worth it. As Donald Knuth said once: Premature optimization is the root of all evil.

Answered By – Jérôme Richard

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *