3

So we tried developing a math class in C# and we did. Comparing results with the original math class for System.Math shows that we are always a little or a lot slower (trig methods particularly).

But the wonder comes when we are using basic methods like absolute value which does not contain loads of code apart from

if(value < 0) return -value;
else return value;

and still we are far behind.

I cannot make this abs method any smaller, using the ternary operator will not help either I guess.

Is it because the System.Math would be written in C? Would it go faster if we write it in native language, though it seems it won't change much I read. Finally, could a dll work faster than a class and if so why and if not… well why too?

Didier L
  • 18,905
  • 10
  • 61
  • 103
Everts
  • 10,408
  • 2
  • 34
  • 45

2 Answers2

6

Continuing with Servé's comment that shows the CLR is written in C++, you'll find that Math.Abs calls fabs or fabsf.

FCIntrinsicSig("Abs", &gsig_SM_Flt_RetFlt, COMDouble::AbsFlt, CORINFO_INTRINSIC_Abs)
FCIntrinsicSig("Abs", &gsig_SM_Dbl_RetDbl, COMDouble::AbsDbl, CORINFO_INTRINSIC_Abs)
/*=====================================AbsFlt=====================================
**
==============================================================================*/
FCIMPL1_V(float, COMDouble::AbsFlt, float f) 
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    FCUnique(0x14);
    return fabsf(f);
FCIMPLEND

/*=====================================AbsDbl=====================================
**
==============================================================================*/
FCIMPL1_V(double, COMDouble::AbsDbl, double d) 
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    return fabs(d);
FCIMPLEND
Community
  • 1
  • 1
user247702
  • 23,641
  • 15
  • 110
  • 157
1

I don't think trivial functions in System.Math are written in C because the overhead of calling out to C would be in many cases much too high. Maybe they are written in raw IL to make them extra fast.

BTW: Why would you write your own math library? This is almost never a good idea.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • 1
    http://stackoverflow.com/questions/8870442/how-is-math-pow-implemented-in-net-framework Math is written in C++ – Serve Laurijssen Sep 18 '13 at 11:17
  • It is part of a project for learning. Indeed, there is no reason to do so since System.Math is already having all that is needed, but it was just a way to learn Taylor series and other algorithm and see how methods are implemented. – Everts Sep 18 '13 at 12:02