BenchmarkDotNet测试异常:float加法性能为何优于int?
为什么float加法测试结果比int快?——Benchmark失真原因解析
你这个反直觉的测试结果,本质是JIT编译器的死代码消除优化导致的,并非float加法真的比int性能更好。
核心问题:无意义运算被JIT彻底移除
你的测试代码中,所有加法运算的结果result都没有被后续使用(既没有返回,也没有参与其他逻辑)。JIT编译器会识别这类对程序输出无影响的“死代码”,直接将运算逻辑从编译后的指令中删除。
此时你测的根本不是加法运算的真实性能,而是空方法的执行开销。不同类型的方法被优化的程度存在差异,导致测试结果完全失真:
int的加法逻辑最简单,JIT可能彻底移除所有运算代码,理论上耗时应该趋近于0,但实际测试中可能因基准测试的精度问题出现波动float的浮点运算相关代码,可能因为JIT优化策略的细节,残留了少量操作,反而在测试中显示出“更快”的假象
如何得到真实的性能数据?
要让测试反映真实的加法性能,必须让运算结果被“有效使用”,常见的两种方式:
- 修改测试方法为返回运算结果:
public class PerformanceTest { [Benchmark] public double CalcDouble() { double firstDigit = 135.543d; double secondDigit = 145.1234; return firstDigit + secondDigit; } [Benchmark] public decimal CalcDecimal() { decimal firstDigit = 135.543m; decimal secondDigit = 145.1234m; return firstDigit + secondDigit; } [Benchmark] public float Calcfloat() { float firstDigit = 135.543f; float secondDigit = 145.1234f; return firstDigit + secondDigit; } [Benchmark] public int Calcint() { int firstDigit = 135; int secondDigit = 145; return firstDigit + secondDigit; } }
- 用
Volatile.Write强制让结果被读取(适合无返回值的测试方法):
public class PerformanceTest { private int _intDummy; private float _floatDummy; private double _doubleDummy; private decimal _decimalDummy; [Benchmark] public void CalcDouble() { double firstDigit = 135.543d; double secondDigit = 145.1234; double result = firstDigit + secondDigit; System.Threading.Volatile.Write(ref _doubleDummy, result); } // 其他方法类似修改... }
真实性能预期
修正测试代码后,你会得到符合常识的结果:
- int:整数加法是CPU最基础的单周期操作,性能最优
- float/double:浮点加法依赖CPU的浮点运算单元(FPU),耗时略高于int(float和double的性能差异通常很小)
- decimal:属于软件实现的高精度类型,加法通过函数调用完成,性能远低于前三者
内容的提问来源于stack exchange,提问作者Pavel Romashuk
相关产品推荐
相关产品推荐

