官术网_书友最值得收藏!

  • Unity Game Optimization
  • Dr. Davide Aversa Chris Dickinson
  • 278字
  • 2021-06-24 12:13:02

Obtaining components using the fastest method

There are several variations of the GetComponent() method, and they each have a different performance cost, so it is prudent to call the fastest possible version of this method. The three overloads available are GetComponent(string), GetComponent<T>(), and GetComponent(typeof(T)). It turns out that the fastest version depends on which version of Unity we are running since several optimizations have been made to these methods through the years; however, if you are using any version of Unity (from Unity 2017 onward), it is best to use the GetComponent<T>() variant.

Let's prove this with some simple testing:

int numTests = 1000000;
TestComponent test;
using (new CustomTimer("GetComponent(string)", numTests)) {
for (var i = 0; i < numTests; ++i) {
test = (TestComponent)GetComponent("TestComponent");
}
}

using (new CustomTimer("GetComponent<ComponentName>", numTests)) {
for (var i = 0; i < numTests; ++i) {
test = GetComponent<TestComponent>();
}
}

using (new CustomTimer("GetComponent(typeof(ComponentName))", numTests)) {
for (var i = 0; i < numTests; ++i) {
test = (TestComponent)GetComponent(typeof(TestComponent));
}
}

The preceding code tests each of the GetComponent() overloads a million times. This is far more tests than would be sensible for a typical project, but it helps to make the relative costs clear.

Here is the result we get when the tests complete (of course, the specific numeric values may be different on your machine):

As you can see, the GetComponent<T>() method is only a tiny fraction faster than GetComponent(typeof(T)), whereas GetComponent(string) is significantly slower than the alternatives. Therefore, it is pretty safe to use either of the type-based versions of GetComponent() because of the small performance difference. However, we should ensure that we never use GetComponent(string) since the outcome is identical, and there are no benefits for the costs incurred. There are some very rare exceptions. Imagine that we were writing a custom debug console for Unity that can parse a user-input string to acquire a component. In this case, we would acquire a component by using the expensive GetComponent(string) only during debugging and diagnostics situations. In these cases, performance isn't too important. On the contrary, for a production-level application, the use of GetComponent(string) is just a needless waste of CPU cycles.

主站蜘蛛池模板: 天台县| 潮州市| 乌恰县| 台州市| 龙海市| 获嘉县| 三门峡市| 安化县| 辰溪县| 晋宁县| 永德县| 旅游| 石门县| 加查县| 西华县| 郴州市| 乐昌市| 油尖旺区| 广州市| 桃园县| 上栗县| 井陉县| 江北区| 寿阳县| 壤塘县| 陇南市| 固安县| 东兴市| 区。| 桂林市| 定远县| 安达市| 理塘县| 陆丰市| 饶平县| 交口县| 惠东县| 汉川市| 常宁市| 黎川县| 广灵县|