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

Obtain Components using the fastest method

There are several variations of the GetComponent() method, and they each have a different performance cost, so it becomes 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, in all later versions of Unity 5 and the initial release of Unity 2017, 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 make the relative costs clear.

Here is the result we get when the tests complete:

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 is no benefit for the costs incurred. There are some very rare exceptions, like if we were writing a custom debug console for Unity, which might parse a user-inputted string to acquire a Component. In any case, these would be used for debugging and diagnostics situations only, where performance isn't too important. For a production-level application, the use of GetComponent(string) is just a needless waste.

主站蜘蛛池模板: 美姑县| 无为县| 罗田县| 依兰县| 湘阴县| 盐山县| 秭归县| 阿坝| 马鞍山市| 息烽县| 江油市| 九台市| 迭部县| 万全县| 芜湖县| 剑阁县| 玛曲县| 洛南县| 大同市| 光山县| 元阳县| 巴楚县| 娱乐| 营山县| 临城县| 舞钢市| 孟州市| 甘谷县| 大同市| 鄂托克旗| 石渠县| 察雅县| 疏附县| 万盛区| 宣汉县| 水富县| 应用必备| 郎溪县| 威远县| 宁晋县| 汕尾市|