Skip to content

Instantly share code, notes, and snippets.

@aalmada
Created December 14, 2016 22:22
Show Gist options
  • Save aalmada/b535b09ed83092b9288ff55d59b3b656 to your computer and use it in GitHub Desktop.
Save aalmada/b535b09ed83092b9288ff55d59b3b656 to your computer and use it in GitHub Desktop.
For loop benchmarking in Unity
using UnityEngine;
public class IterationTest : MonoBehaviour {
// Use this for initialization
void Start () {
const int count = 100000000;
int[] a = new int[count];
int total;
var watch = new System.Diagnostics.Stopwatch();
for (var i = 0; i < count; i++)
a[i] = Random.Range(0, 100);
total = 0;
watch.Start();
foreach (var i in a)
total += i;
watch.Stop();
Debug.Log("foreach: " + watch.ElapsedMilliseconds);
watch.Reset();
total = 0;
watch.Start();
for (var i = 0; i < count; i++)
total += a[i];
watch.Stop();
Debug.Log("for: " + watch.ElapsedMilliseconds);
watch.Reset();
total = 0;
watch.Start();
for (var i = count; --i >= 0;)
total += a[i];
watch.Stop();
Debug.Log("reversed for: " + watch.ElapsedMilliseconds);
watch.Reset();
}
// Update is called once per frame
void Update () {
}
}
@aalmada
Copy link
Author

aalmada commented Dec 14, 2016

foreach: 972
for: 742
reversed for: 566

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment