最近在优化摄像机部分代码,抽了个时间对物理投射这块进行了系统性的测试,发现了不少东西
测试工程下载地址:
测试方式:
在某半径内随机若干Cube,然后以中心点发射各种投射进行测试
使用Unity5.4.1版本,并用Profiler和StopWatch进行测试并截图,比较性能和GC差异
由于胶囊之类的投射实在太慢了,我改用1000次调用进行测试,NonAlloc缓存数组长度为20
一些投射都做了距离限定
脚本基本如下:
for (int i = 0; i < 1000; i++){ Physics.BoxCastAll(transform.position, Vector3.one * 2f, Vector3.forward, Quaternion.identity, 0);}
测试结果:
名称 | 速度 | GC Alloc |
Raycast | 1ms | - |
RaycastNonAlloc | 2ms | - |
RaycastAllTest | 2ms | 273.4KB |
Linecast | 1ms | - |
BoxCastTest | 17ms | - |
BoxCastNonAllocTest | 18ms | - |
BoxCastAllTest | 20ms | 1.5MB |
CheckBoxTest | 1ms | - |
OverlapBoxTest | 62ms | 2.4MB |
OverlapBoxNonAllocTest | 24ms | - |
CapsuleCastTest | 162ms | - |
CapsuleCastNonAllocTest | 227ms | - |
CapsuleCastAllTest | 336ms | 12.7MB |
CheckCapsuleTest | 1ms | - |
OverlapCapsuleTest | 84ms | 2.1MB |
OverlapCapsuleNonAllocTest | 30ms | - |
SphereCastTest | 96ms | - |
SphereCastNonAllocTest | 171ms | - |
SphereCastAllTest | 226ms | 8.8MB |
CheckSphereTest | 1ms | - |
OverlapSphereTest | 33ms | 1.5MB |
OverlapSphereNonAllocTest | 16ms | - |
射线和线段的开销非常小,撇开这个可以发现,性能消耗的顺序是这样的
从小到大:
CheckXXX -> OverlapXXX -> XXXCast
其中Check系列方法的开销极小
从投射物来看,从小到大分别是:Box > Sphere > Capsule