unity 性能优化记录

这里单独开一篇记录unity不限于unity的优化记录。

开始之前先明白几个专业术语

GC Alloc:表示正在执行内存分配操作。

GC.Collect:表示正在执行内存释放操作。

1.update里尽量不要声明局部变量,就算是值类型也因避免。

如:

public override void Update()
    {
        float d = playerCtrl.player._Attribute.AtkSpeed;

        if (atkInterval != d)
        {
            atkInterval = playerCtrl.player._Attribute.AtkSpeed;
            atkTime = 1f / atkInterval;
        }
        if (addTime >= atkTime)
        {
            AttackNoraml();
            addTime %= atkTime;
        }
        addTime += Time.deltaTime;
    }

这里最大的消耗就是第一行的变量d的声明。这样声明后在profiler中每隔一段时间就有一个Update().GC.Collect 为32kb的消耗。

float d = 0;
    public override void Update()
    {
        d = playerCtrl.player._Attribute.AtkSpeed;
}

 

修改为:全局变量后GC.Collect 消失。

2.所有需要用到除法的地方应尽量替换成乘法。

float num = 10/2;

可修改为:

float num = 10*0.5f;

 3.foreach替换为for

static void Main(string[] args)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("C#", "4.5");
    dict.Add("Java", "8");
    dict.Add("Python", "3");
    Dictionary<string, string>.Enumerator etor = dict.GetEnumerator();
    while (etor.MoveNext())
    {
        Console.WriteLine("key = {0}, value = {1}",etor.Current.Key, etor.Current.Value);
    }
}

foreach存在bug,会导致GC Alloc,并且效率低下;
使用GetEnumerator代替,没有GC,并且速度快10倍!

建议迭代操作中,List使用for,Dictionary使用GetEnumerator

测试链接:https://www.jianshu.com/p/cacea8e30142

4.用Input.GetTouch()和Input.touchCount()来代替Input.touches,或者用Physics.SphereCastNonAlloc()来代替Physics.SphereCastAll()。

 

https://blog.csdn.net/znybn1/article/details/76464896 这篇文章一定要读完

https://www.cnblogs.com/zblade/p/6424405.html GPU优化策略 一定要读完哦

https://www.cnblogs.com/zblade/p/6445578.html GC优化策略  这个包含了GC和渲染优化 一定要读完哦

posted @ 2020-01-02 14:25  大刀乱飞  阅读(250)  评论(0)    收藏  举报