标签:
Which of the following should execute faster?
那种执行更快呢?
1 2 3 4 5 | if(gameObject.tag == "Player") if(gameObject.tag == "Player".GetHashCode()) if(gameObject.tag == toCompare) if(gameObject.tag.GetHashCode() == hashToCompare) if(gameObject.CompareTag(toCompare)) |
If you guessed any of them, you are wrong. That’s right, calling them 10000 times a second there is no single method that consistently executes faster than the others. (Not entirely true but I’m making a point here.)
如果你猜是其中的一个,你就错了。每秒调用他们10000次,效率其实差不多。 (并非完全如此,但我的实验室这样的。)
So the compiler optimised out the literal string for us, that’s good to know. Lets look at the profile results.
所以说是编译器优化了字符串,让我们使用profile看看结果。
J’accuse. Everything is allocing but CompareTag, the method in gameobject that is recommended by Unity as the method to, you guessed it, compare tags. Where at all possible use CompareTag. the GC is your enemy. It’s an interesting situation. The alloc comes from get_tag(), which is triggered by the .tag property, which could be a call to unity native code that results in a mono string being created or just due to the immutable nature of strings in mono. I know I’m guilty of it too but if you can find a .tag anywhere in your code base do your darnedest to get rid of it.
除了CompareTag其他方法都会分配内存,而CompareTag内存申请应该是在Unity3D内部。
Speaking of strings. String concat or string.Format or StringBuilder for simple wave counter in JSD.
1
2
3
4
5
6
7
8
9
10
11
|
//sb
is a StringBuilder
sb.Length
=
0;
sb.Append(WaveString);
//"Wave:
"
sb.Append(lvl.curIndex);
sb.Append(post);
//"
of "
sb.Append(lvl.infos.Count);
txt.text
=
sb.ToString();
txt.text
=
"Wave:
"
+
(lvl.curIndex).ToString()
+
"
of "
+
lvl.infos.Count.ToString();
txt.text
=
string.Format("Wave:
{0} of {1}",
lvl.curIndex,
lvl.infos.Count);
|
Format looks nicer, kinda, probably a lot if you like printf.
Well crap, Format is out, it’s the slowest and the most trashy. StringBuilder vs regular concatenation is a bit trickier. For my purposes I can avoid calling the function for all but when the current wave actually changes, so less than once a second, keeping the alloc as low as possible suits me.
Format效率最差。stringbuilder和普通字符串的连接有些棘手。少于每秒调用一次,alloc比较低的适合我(StringBuilder)。
Unity Optimisation Basics Part 3
标签:
原文地址:http://blog.csdn.net/claien/article/details/42676647