Skip to content

Instantly share code, notes, and snippets.

@sarbian
Created December 23, 2015 14:18
Show Gist options
  • Save sarbian/b2f96d36bef61e765804 to your computer and use it in GitHub Desktop.
Save sarbian/b2f96d36bef61e765804 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections.Generic;
public class ForeachTest : MonoBehaviour
{
private string _testString = "this is a test";
private List<string> _testList;
private const int _numIterations = 10000;
void Start()
{
_testList = new List<string>();
for (int i = 0; i < _numIterations; ++i)
{
_testList.Add(_testString);
}
}
void Update()
{
Profiler.BeginSample("ForeachIter");
ForeachIter();
Profiler.EndSample();
Profiler.BeginSample("WhileIter");
WhileIter();
Profiler.EndSample();
Profiler.BeginSample("ForLoop");
ForLoop();
Profiler.EndSample();
}
private void ForeachIter()
{
string s;
for (int i = 0; i < 1000; ++i)
{
foreach (string str in _testList)
{
s = str;
}
}
}
private void ForLoop()
{
string s;
for (int i = 0; i < 1000; ++i)
{
for (int index = 0; index < _testList.Count; index++)
{
string str = _testList[index];
s = str;
}
}
}
private void WhileIter()
{
string s;
string item;
for (int i = 0; i < 1000; ++i)
{
var enumerator = _testList.GetEnumerator();
while (enumerator.MoveNext())
{
item = enumerator.Current;
s = item;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment