Iterating over an array or a list that has no element, foreach seems very slow compared to for. Running below code, the result I got is:
3ms
143ms
7ms
Is foreach really slow or am I doing something wrong?
var l = new List<int>();
var watch = new Stopwatch();
var test = 0;
watch.Start();
for (int i = 0; i < 10000000; i++)
if (l.Count > 0)
test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
foreach (var item in l)
test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
for (int j = 0; j < l.Count; j++)
test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);