几个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关键字

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值