Performance Enhancer – AddRange instead of foreach-add for collections copy!

If the source collection needs to be copied to destination list, its better to use addRange instead of foreach-add while copying. (Mere assigning source collection to destination collection is not what intended as it won’t create a new memory for destination list.)
Say I have a source list of students – Student List & I need to copy only Student ids to Destination list- IdsList.
The code can be –
IdsList = new List();
StudentList.ForEach(a=> IdsList.Add(a.Id));

The above code takes some extra oeverhead wrt runtime allocation.
Instead we can go with
IdsList = new List();
IdsList.AddRange(StudentList.Select(a=>a.Id));

In the second process, it allocates the memory for entire IdsList onetime & copies at once. where as in first case, for every iteration in ForEach, it allocates memory for each single item while adding to IdsList which is an additional overhead if it is mere copy kinda.

Advertisements