Skip to content

Instantly share code, notes, and snippets.

@rzubek
Created June 16, 2014 04:24
Show Gist options
  • Save rzubek/ce7ecf303399daee1fdf to your computer and use it in GitHub Desktop.
Save rzubek/ce7ecf303399daee1fdf to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
namespace Benchmark.Test
{
class InstanceSpawner : MonoBehaviour
{
Transform cachedtransform;
public void Start()
{
StartCoroutine(RunTests());
}
IEnumerator RunTests()
{
for (int i = 0; i < 5; i++)
{
RunTest();
yield return new WaitForSeconds(2);
}
}
void RunTest()
{
Vector3 local = new Vector3(0, 0, 0);
this.cachedtransform = this.GetComponent<Transform>();
float sum = 0f;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
// 1. base case
sum += local.z;
// 2. transform cached in member var
// sum += cachedtransform.position.z;
// 3. transform getter from MonoBehaviour
// sum += transform.position.z;
// 4. transform getter from GameObject
// sum += gameObject.transform.position.z;
// 5. untyped GetComponent from MonoBehaviour
// sum += (GetComponent(typeof(Transform)) as Transform).position.z;
// 6. untyped GetComponent from GameObject
// sum += (gameObject.GetComponent(typeof(Transform)) as Transform).position.z;
// 7. typesafe GetComponent from MonoBehaviour
// sum += GetComponent<Transform>().position.z;
// 8. typesafe GetComponent from GameObject
// sum += gameObject.GetComponent<Transform>().position.z;
// 9. string GetComponent from MonoBehaviour
// sum += (GetComponent("Transform") as Transform).position.z;
// 10. string GetComponent from GameObject
// sum += (gameObject.GetComponent("Transform") as Transform).position.z;
}
stopwatch.Stop();
UnityEngine.Debug.Log("SECONDS ELAPSED: " + stopwatch.Elapsed.TotalSeconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment