03 Aug 2011

Found this little C# compiler optimisation which is really cool. Here is start code

int y = 0;
int x = 10;

if (x * 0 == 0)
{
    y = 123;
}

Console.WriteLine(y);

If you know a bit of math, anything multiplied by 0 always equals 0 (line 4). So the compiler optimises that out and then because x is never used that is also optimised out and you end up with

int y = 0;

if (0 == 0)
{
    y = 123;
}

Console.WriteLine(y);
So very smart Smile

Comments

Jethro's picture

Would of been cool if the If statement was also removed, as it is always true. But still not bad.

Matt's picture

Nice.
A friend showed me a similar thing the other day where he had a for loop that was essentially doing nothing, and the compiler skipped over it.

Add new comment