Can anyone explain, why the first execution of this Code takes about 4 times longer than every further execution? (Press SpaceBar).
I thought that when a list is initialized with a given size (in my case: List speedTestList = new List(100000000), there shouldnt be any allocation-issues because the list doesnt need to resize on a “List.Add()”?
It even makes less sense to me, because i’m stopping the “Contains” function, which shouldnt actually vary that much at all, because the list doesnt change?
using UnityEngine;
using System.Diagnostics;
using System.Collections.Generic;
public class PerformanceMeasure : MonoBehaviour
{
List<Vector2> speedTestList = new List<Vector2>(100000000);
Stopwatch sw = new Stopwatch();
// Use this for initialization
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Vector2 tmp2;
// Fill Lists
for (int i = 0; i < speedTestList.Count; i++) speedTestList.Add(new Vector2(0, i));
sw.Start();
for (int i = 0; i < speedTestList.Count; i++)
{
if (speedTestList.Contains(new Vector2(0, i)))
{
tmp2 = new Vector2(0, i);
}
}
sw.Stop();
speedTestList.Clear();
UnityEngine.Debug.Log("Elapsed Ticks = " + sw.ElapsedTicks);
sw.Reset();
}
}
}
Hmmm… why does it say then, that the List.count is 0 when you Log it before adding the additional 100000000 Vector2?
Also, the time doesnt change if i perform a List.Clear() before adding the Vector2 into the list.
EDIT:
I just noticed a problem when i fill the list… apparently it seems the “filling” is never performed, because the .count is 0 on startup… double checking now
After editing the List-filling to work properly, the performance check now seem stable every time i perform it. @Malleck666 thanks for pointing me into the right direction!
Actually, your code snippet misses the brace. His snippet is correct.
However, there is another fatal flaw in his logic which has something to do with the nature of the idea behind a dynamically growing list.
Just have a look at the condition and the actual code to execute.
If you happen to start adding elements in that loop when you initially start with ‘i < speedTestList.Count == true’, you’ll be running into an infinite loop. The situation leads to some kind of freeze, while the list actually continues to grow until you run out off memory.