I'm trying to speed up a loop, which is cloning 2_500_000 objects. The clone itself is taking 800 ms for the entire loop but when I'm adding them to a list, it's taking 3 seconds..
List<T> list = new List<T>();
Stopwatch sw = new Stopwatch();
sw.Start();
foreach(T entity in listSource)
{
T entityCloned = GetEntityClone(entity); // Taking 800ms totally
if (entityCloned != null)
list.Add(entityCloned);
}
sw.Stop();
Could you please help me to find out why those Add
s are taking so much time?
I saved some time (around 33%) by using array instead of list:
MyObject class defitinion:
public class MyObject
{
public int Id { get; set; }
public bool Flag { get; set; }
public static MyObject GetEntityClone(MyObject obj)
{
if (obj == null) return null;
var newObj = new MyObject()
{
Id = obj.Id,
Flag = obj.Flag
};
return newObj;
}
}
Code:
var sourceList = new List<MyObject>();
// let's mock the source data, every 27th element will be null
for (int i = 0; i < 2500000; ++i)
{
if (i % 27 != 0)
sourceList.Add(new MyObject { Id = i, Flag = (i % 2 == 0) });
}
var destArray = new MyObject[2500000];
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine(sw.ElapsedMilliseconds);
var currentElement = 0;
for (int i = 0; i < sourceList.Count; ++i)
{
MyObject entityCloned = MyObject.GetEntityClone(sourceList[i]);
if (entityCloned != null)
destArray[currentElement++] = entityCloned;
}
var result = new MyObject[currentElement];
Array.Copy(destArray, 0, result, 0, currentElement);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);