C#:Randall Cook的答案的变体我喜欢,因为它比扩展方法更能保持代码的数学“外观”,我喜欢这样,它是使用包装器,但对调用使用函数引用,而不是包装它们。我个人认为这会使代码看起来更简洁,但是基本上它是在做相同的事情。
我敲了一些LINQPad测试程序,包括Randall的包装函数,我的函数引用和直接调用。
函数引用的调用基本上与直接调用花费相同的时间。打包的函数始终较慢-尽管数量不多。
这是代码:
void Main()
{
MyMathyClass mmc = new MyMathyClass();
System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
for(int i = 0; i < 50000000; i++)
mmc.DoStuff(1, 2, 3);
"Function reference:".Dump();
sw.Elapsed.Dump();
sw.Restart();
for(int i = 0; i < 50000000; i++)
mmc.DoStuffWrapped(1, 2, 3);
"Wrapped function:".Dump();
sw.Elapsed.Dump();
sw.Restart();
"Direct call:".Dump();
for(int i = 0; i < 50000000; i++)
mmc.DoStuffControl(1, 2, 3);
sw.Elapsed.Dump();
}
public class MyMathyClass
{
// References
public Func<double, double> sin;
public Func<double, double> cos;
public Func<double, double> tan;
// ...
public MyMathyClass()
{
sin = System.Math.Sin;
cos = System.Math.Cos;
tan = System.Math.Tan;
// ...
}
// Wrapped functions
public double wsin(double x) { return Math.Sin(x); }
public double wcos(double x) { return Math.Cos(x); }
public double wtan(double x) { return Math.Tan(x); }
// Calculation functions
public double DoStuff(double x, double y, double z)
{
return sin(x) + cos(y) + tan(z);
}
public double DoStuffWrapped(double x, double y, double z)
{
return wsin(x) + wcos(y) + wtan(z);
}
public double DoStuffControl(double x, double y, double z)
{
return Math.Sin(x) + Math.Cos(y) + Math.Tan(z);
}
}
结果:
Function reference:
00:00:06.5952113
Wrapped function:
00:00:07.2570828
Direct call:
00:00:06.6396096