几个C#测试说明的问题

1、长引用与短引用

var time1 = System.DateTime.Now;

int loopCount = 1000 * 1000 * 100;
var test1 = test.wrr.test;
for (int i = 0; i < loopCount; i++){
    if (test1.haha){
    }
}
Debug.Log("[Use Time]_short " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
for (int i = 0; i < loopCount; i++){
    if (test.wrr.test.haha){
    }
}
Debug.Log("[Use Time]_long " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
bool direct = test.wrr.test.haha;
for (int i = 0; i < loopCount; i++){
    if (direct){
    }
}
Debug.Log("[Use Time]_direct " + (System.DateTime.Now - time1).TotalMilliseconds);

测试结果及说明

[Use Time]_short 687
[Use Time]_long 772
[Use Time]_direct 669
使用局部变量是最省性能的一种方式,其次是短引用。
但每种方式的性能差距其实并不大。

2、类型判断

var time1 = System.DateTime.Now;
int loopCount = 1000 * 1000 * 100;

for(int i=0;i<loopCount;i++){
    if(unit is Creature){
    }
}
Debug.Log("[Use Time]_Is " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
for (int i = 0; i < loopCount; i++){
    if (unit.IsCreature){
    }
}
Debug.Log("[Use Time]_get " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
for (int i = 0; i < loopCount; i++){
    if (unit.IsWarrior){
    }
}
Debug.Log("[Use Time]_directBool " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
for (int i = 0; i < loopCount; i++){
    if (unit.IsCreatureByType){
    }
}
Debug.Log("[Use Time]_getByType " + (System.DateTime.Now - time1).TotalMilliseconds);

time1 = System.DateTime.Now;
for (int i = 0; i < loopCount; i++){
    if (unit.IsWarriorByVirtual){
    }
}
Debug.Log("[Use Time]_virual " + (System.DateTime.Now - time1).TotalMilliseconds);

测试结果及说明

[Use Time]_Is 878
[Use Time]_get 1659
[Use Time]_directBool 715
[Use Time]_getByType 1746
[Use Time]_virual 1958
可以看出,直接使用字段是最省时间的,其次使用is关键字。如果使用get索引器,性能会再次下降,使用虚索引器是最费时间的。
五种测试中,虽然差距仍并不是特别大,但还是建议使用字段或者is关键字

你可能感兴趣的:(游戏编程)