Created
December 14, 2016 22:22
-
-
Save aalmada/b535b09ed83092b9288ff55d59b3b656 to your computer and use it in GitHub Desktop.
For loop benchmarking in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 () { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
foreach: 972
for: 742
reversed for: 566