In quite a few cases I happen to be in a situation that I was wondering if I had to perform an IF check before setting a variable (and increase the method's complexity) or if this is done internal by Windows or the Framework.
As an example, assume we have an event that is being trigger constantly such as the Form's MouseMove event. Which one of those methods would be better to use ? Is calling this.Cursor = Cursors.SizeNWSE; being check internally as well to ensure that no action will take place if it is not needed or does it blindly execute the code ?
Example A:
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X - this.Width > -16 && e.Y - this.Height > -16)
{
this.Cursor = Cursors.SizeNWSE;
}
else
{
this.Cursor = Cursors.Arrow;
}
}
Example B:
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X - this.Width > -16 && e.Y - this.Height > -16)
{
if (this.Cursor != Cursors.SizeNWSE)
this.Cursor = Cursors.SizeNWSE;
}
else
{
if (this.Cursor != Cursors.Arrow)
this.Cursor = Cursors.Arrow;
}
}
In short: Yes, making the check is most efficient by much.
In depth:
I've tested and compared (the code runs on the Form's Load event), and was surprised to see an actual difference.
Here is the code I've used to test:
this.Cursor = Cursors.SizeNWSE;
var sw1 = Stopwatch.StartNew();
for (var i = 0; i < 10000000; i++)
{
this.Cursor = Cursors.SizeNWSE;
}
sw1.Stop();
var sw2 = Stopwatch.StartNew();
for (var i = 0; i < 10000000; i++)
{
if (this.Cursor != Cursors.SizeNWSE)
{
this.Cursor = Cursors.SizeNWSE;
}
}
sw2.Stop();
And then I swapped between the two, running the second case before the first, just to be sure. And the results are certain!
With If: 00:00:00.8065328
Without If: 00:00:20.8631726
A huge difference! Running without the check was more than 20 times slower than running with the check.
This means that when assigning a Cursor, there is no check to determine if the assignment can be ignored.
But what happens if the assignment really can't be ignored? What if it's a different Cursor each time?
Good question! The answer is that further testing shows very little difference between the yes-check and the no-check versions, when the cursors assigned are NEVER the same as the actual cursor at the moment of the assignment, so the assignment was never redundant. The difference was obviously the extra time it took to perform the checks.
ReSharper may warn you that the check is redundant ("Redundant check before assignment") but is isn't, in this case! Certainly not.
If you're doing it a LOT, you want to make the check.
On a MouseMove event, I would suggest making the check, to prevent laggy mouse. Even if you don't notice it, it might show on slower machines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With