Unity教程之-Unity中SendMessage和Delegate效率比较

 

本篇文章我们来看下,Unity中SendMessage和Delegate效率比较 ,但是网上都说,他们之间的差距,delegate比较快,效果高。怎么个高法呢?还是自己来测试下时间。 故此, 个人之用来比较下时间差别。

贴上代码:


using UnityEngine;
using System.Collections;
public class DelegateBasic : MonoBehaviour
{
static int loopNumber = 5000000;
//define my delegate statement.
public delegate void MyDelegate(string arg1);

//create my delegate object
public MyDelegate myDelegate;

//need some values to debug time spent.
bool isStart;
float timeStart;
int count;

bool isStartSendMessage;

// Use this for initialization
void Start()
{
myDelegate += myFunciton1;
//myDelegate += myFunciton2;
}

// Update is called once per frame
void Update()
{
if (isStart)
{
isStart = false;
count = 0;
timeStart = Time.realtimeSinceStartup;
Debug.Log("Start = " + timeStart);
for (int i = 0; i < loopNumber; i++)
{
if (myDelegate != null) myDelegate("");
}
}

if (isStartSendMessage)
{
isStartSendMessage = false;
count = 0;
timeStart = Time.realtimeSinceStartup;
Debug.Log("Start = " + timeStart);
for (int i = 0; i < loopNumber; i++)
{
this.gameObject.SendMessage("myFunciton1", "", SendMessageOptions.DontRequireReceiver);
}
}
}
void OnGUI()
{
if (GUILayout.Button("INVOKE Delegate"))
{
isStart = true;
}

if (GUILayout.Button("SendMessage"))
{
isStartSendMessage = true;
}

}

void myFunciton1(string s)
{
count++;
if (count == loopNumber)
{
Debug.Log("End = " + Time.realtimeSinceStartup);
Debug.Log("Time Spent = " + (Time.realtimeSinceStartup - timeStart));
}
}

}

二、说明

代码基本没有做更改,删掉了没用的函数。也名字也带着呢!!在此表示感谢!!!

但说道具体测试,要每次都需要重新开始,才能计时。要不就会有问题,后测试的就会产生多次循环。

三、效率比较

系统配置:”Win7 64位,i7处理器 16G内存,英伟达660显卡”

数据

对比为倍数关系!!也就说,随着次数增加,效率差距越来越大!!!