C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The angle brackets are part of the declaration type, not numeric operators. They are treated differently in the language.
AddRange: For adding many elements at once, you can use the AddRange method on List for less code.
AddRange, InsertRangeC# program that uses Add method
using System.Collections.Generic;
class Program
{
static void Main()
{
// Add first 4 numbers to the List.
List<int> primes = new List<int>();
primes.Add(2);
primes.Add(3);
primes.Add(5);
primes.Add(7);
}
}
And: Because the Test type is a reference type, the List stores references to the Test objects on the managed heap.
C# program that adds objects to List
using System.Collections.Generic;
class Program
{
static void Main()
{
// Add 3 objects to a List.
List<Test> list = new List<Test>();
list.Add(new Test(1, 2));
list.Add(new Test(3, 4));
list.Add(new Test(5, 6));
}
class Test
{
int _a;
int _b;
public Test(int a, int b)
{
_a = a;
_b = b;
}
};
}
Version 1: This code creates a new, empty List, and then appends 3 elements from an array directly with AddRange.
Version 2: This version of the code uses a foreach-loop and calls Add() on each element of the 3-element int array.
Result: It is faster to call Add() over each element of the array. Using AddRange seems to make the program slower.
BenchmarkC# program that benchmarks List Add, AddRange
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
int[] array = { 10, 20, 30 };
// Version 1: use AddRange.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
var list = new List<int>();
list.AddRange(array);
if (list.Count != 3)
{
return;
}
}
s1.Stop();
// Version 2: use Add.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
var list = new List<int>();
foreach (int value in array)
{
list.Add(value);
}
if (list.Count != 3)
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
}
}
Output
131.78 ns AddRange
25.01 ns Add
Info: Resizing an array is slow, but if you are using a reference type in your List, the references themselves are small and fast to copy.
Tip: Faster copying is an advantage to reference types. References are also faster to copy to arguments during method calls.
Then: It doubles the array size each time it runs out of room during an Add call.
Capacity