11

Might be a silly question, but is there any reason to use Math.Sign?

Is there a speed/optimization thing with using Math.Sign rather than just using an if statement? Perhaps just a best practice/code readability preference?

if (rayDirX < 0) 
    stepX = -1; 
else 
    stepX = 1;

//----------

stepX = (rayDirX < 0) ? (-1) : (1);

//----------

stepX = Math.Sign(rayDirX);
Mythics
  • 773
  • 1
  • 10
  • 19
  • 2
    I'm so glad that I'm not the only one who thinks this method is pretty much pointless... – Mike G Dec 04 '12 at 16:07
  • A method name is more descriptive than an algebraic expression, and encapsulates the constants to prevent repetition and the possibility for error. – Dan Puzey Dec 06 '12 at 10:42

4 Answers4

5

I doubt there is a functional difference or much, if any, perf difference but the Math.Sign version is a little more visibly straight forward. Especially in your example where the Type of rayDirX is not declared. But it's pretty subtle and I wouldn't criticize you for using either.

EDIT:

And one other thing, your example above has a slight bug. In the case of 0 Math.Sign will return 0. Here is the decompiled code out of the framework for Math.Sign:

public static int Sign(int value)
{
  if (value < 0)
  {
    return -1;
  }
  if (value > 0)
  {
    return 1;
  }
  return 0;
}
justin.m.chase
  • 13,061
  • 8
  • 52
  • 100
  • Ten years later latest C# version also compares against 0.0, which makes it a little bit uglier and slower – Trap Aug 21 '22 at 01:40
4

Math.Sign can be used as part of a larger expression. You could also get the sign for use in an expression via the ternary operator, but not everything thinks the ternary operator is all that readable.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
4

There is a functional difference: Math.Sign has three possible return values, and will return zero if the input is 0. You can't do that with a (single) ternary operator.

(Source)

Also, a method name is more descriptive than an algebraic expression, and encapsulates the constants to prevent repetition and the possibility for error.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
0

I think its mostly a readability issue. I didn't see anything in the reference that points to any differences. But as Joel said, Math.sign(rayDirX) is much easier to use as a part of a larger expression that the if block or conditional expression.

Corwin01
  • 479
  • 3
  • 7
  • 24