我测试了我在Linux上网本上使用VisualVM 1.3.7 编写的Java光线跟踪器的性能.我用剖面仪测量.
为了好玩,我测试了使用getter和setter以及直接访问字段之间的区别.getter和setter是标准代码,没有添加.
我没想到会有任何分歧.但直接访问代码的速度较慢.
这是我在Vector3D中测试的样本:
public float dot(Vector3D other) {
return x * other.x + y * other.y + z * other.z;
}
Run Code Online (Sandbox Code Playgroud)
时间:1542毫秒/ 1,000,000次调用
public float dot(Vector3D other) {
return getX() * other.getX() + getY() * other.getY() + getZ() * other.getZ();
}
Run Code Online (Sandbox Code Playgroud)
时间:1453毫秒/ 1,000,000次调用
我没有在微基准测试中测试它,而是在光线跟踪器中测试.我测试代码的方式:
我至少为这两个代码运行了20,000,000次调用.我关闭了任何我不需要的程序.我设置CPU的性能,所以我的CPU时钟是最大的.每时每刻.
第二个代码如何快6%?