Some Results
//test a
double functional(double a, double b)
{
return a + b;
}
//test b
double nonfunctional()
{
return a + b;
}
//test c
double functional_no_param()
{
double a = rand.NextDouble();
double b = rand.NextDouble();
return a + b;
}

For Test B the variables a and b are class variables of type double and are set to rand.NextDouble() prior to the function call.
I was getting odd results before because I was simply declaring a variable, setting it to rand.NextDouble() and returning it. In that case the compiler was optimizing the code to essentially be “return rand.NextDouble()” That’s why it appeared that the functional way was faster.
However, once you start passing parameters you start to see a lot of overhead. You can see that it’s actually faster to declare a local variable (Test C) than to pass the values in (Test A). But, optimally the variables are predefined and you simply set the values.
So while functional programming may be easier to test and reuse, it suffers significant slow downs.
Safe mode is probably faster because C# may be switching modes. The “unsafe” code is the loop that calls the function a bunch of times. So you don’t want safe code to call unsafe code. You lose performance that way instead of gain it.
Test B benefits from unsafe because most of the work is done in the unsafe portion of code.
Leave a comment
You must be logged in to post a comment.