3

Different Ways to Add Values to a C# Array

 2 years ago
source link: https://code-maze.com/add-values-to-csharp-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Different Ways to Add Values to a C# Array

Publisher Logo

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy.

Different Ways to Add Values to a C# Array

Posted by Code Maze | Updated Date Aug 22, 2022 | 2

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we are going to learn about the different ways we can add values to a C# array.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

How to Add Values to a C# Array

Arrays in C# can have a fixed size. We also know that we can assign values to an array at the time of initialization.

After we initialize an array, we might want to add value to the specific index, change the array size to add more values or copy the values from one array into another.

Let’s have a look at the different approaches to adding values to an array. After that, we’ll wrap things up with a performance benchmark to find which approach is the most efficient.

Array Index Initializer

Using this approach, we can set the value using the specified index or position of an array.

Let’s create a simple integer array of size 3:

var array = new int[3];
var array = new int[3];

In this array, we have 3 indexes namely 0, 1, and 2.

In order to set the value at these indexes, we can use the index initializer:

array[0] = 100;
array[1] = 101;
array[2] = 102;
array[0] = 100;
array[1] = 101;
array[2] = 102;

As we can see, each statement uses an array index to set its value.

However, it is also important to note that if we use any invalid index, then we are thrown the IndexOutOfRangeException. Hence, we need to ensure that the index is always within the range (arraySize - 1).

Array.SetValue() Method

The next approach is to use the SetValue() method available in Array class:

array.SetValue(value: 100, index: 0);
array.SetValue(value: 101, index: 1);
array.SetValue(value: 102, index: 2);
array.SetValue(value: 100, index: 0);
array.SetValue(value: 101, index: 1);
array.SetValue(value: 102, index: 2);

We can directly invoke the SetValue() method on an array itself. Please note that we need to provide the value as the first parameter and the index as the second parameter. Apart from this, there are multiple overloads available for different use cases.

Again, this method also throws IndexOutOfRangeException for incorrect array index.

Array.CopyTo() Method

One more approach to add values to an array is by using the Array.CopyTo() method. 

Using this method, we can copy all the elements from one array to another array starting at the specified target array index.

To demonstrate this, let’s declare our first array with size 3:

var array1 = new int[3];
var array1 = new int[3];

After that, let’s create our second array with some elements:

var array2 = new int[] { 100, 101, 102 };
var array2 = new int[] { 100, 101, 102 };

Now, in order to copy all the elements from array2 to array1, we can invoke the CopyTo() method directly on the source array:

array2.CopyTo(array1, 0);
array2.CopyTo(array1, 0);

Here, the first parameter is the target array and the second parameter is the starting index of the target array. This method overwrites the elements on the target array. Another important factor is that the target array should have enough size to hold the copied elements.

There’s also another method Array.Copy() that is similar to Array.CopyTo(). The difference is that it copies a range of elements from the source to the target.

Array.Resize() Method

While we won’t use this method in the benchmark since it doesn’t add values to the array, it’s important to know how to use it because it is a part of adding values to the array in some cases.

Using the Array.Resize() method, we can change the size of an array and then add values to it. We can either increase or decrease an array size using this method.

Let’s say, we have an empty array:

var array = Array.Empty<int>();
var array = Array.Empty<int>();

In order to resize this array to hold 3 elements, we can simply do:

Array.Resize(ref array, 3);
Array.Resize(ref array, 3);

Here, we are passing the reference to an array using the ref keyword as the first parameter and the new array size as the second parameter.

After that, we can use one of the existing ways of adding values to an array in C#.

Add Values to a C# Array by Using Lists

Another approach that we can use is the  List<T> class. We can add elements to the list and then convert it to an array. 

Let’s define a simple list of integers using the List<T> class:

var list = new List<int>();
var list = new List<int>();

Once we have the list object in place, we can add elements to it using the Add() method:

list.Add(100);
list.Add(101);
list.Add(102);
list.Add(100);
list.Add(101);
list.Add(102);

Finally, we can convert the list to an array using ToArray() method:

var array = list.ToArray();
var array = list.ToArray();

This method works well for scenarios we don’t know the size of the array upfront.

LINQ Concat() Method

Next on, there is the Concat() method in LINQ. This method concatenates two sequences into a single sequence. 

Let’s say we have an array and we need to concatenate all the values from another array, then we can use this method.

To give an example, let’s create our first array with an empty size:

var array1 = Array.Empty<int>();
var array1 = Array.Empty<int>();

Our second array contains some values:

var array2 = new int[] { 100, 101, 102 };
var array2 = new int[] { 100, 101, 102 };

Now, let’s concatenate the two arrays into a single one:

array1 = array1.Concat(array2).ToArray();
array1 = array1.Concat(array2).ToArray();

Here, we’ve used the Concat() method to concatenate two arrays and then we invoked the ToArray() method to convert it back to an array.

LINQ Append() Method

Another approach to adding values to an array is to use the Append() method in LINQ. Using this method, we can add values to the end of the sequence. 

Let’s create a simple empty array:

var array = Array.Empty<int>();
var array = Array.Empty<int>();

Now, let’s append the values using the Append() method:

array = array.Append(100).ToArray();
array = array.Append(100).ToArray();

Here, the Append() method returns IEnumerable<T>. But, if we want an array, we can convert it back using the ToArray() method.

In case we want to add an element at the start of the sequence, we need to use Prepend() method.

Performance Benchmark

Now, let’s dive into the interesting part which is performance comparison. We’ll use the BenchmarkDotNet library to do the benchmark for us.

In this benchmark, we’ll use arrays of different sizes and then compare which approach performs the best in adding values to the array.

Let’s look at one of the approaches that we use for benchmark:

public static int[] ArrayIndexInitializer(int arraySize)
var array = new int[arraySize];
for (var index = 0; index < arraySize; index++)
array[index] = index;
return array;
public static int[] ArrayIndexInitializer(int arraySize)
{
    var array = new int[arraySize];
    for (var index = 0; index < arraySize; index++)
    {
        array[index] = index;
    }

    return array;
}

We assign the values to an array in a loop of varying sizes. The other approaches work similarly and you can check the source code if you’re interested.

Benchmark With 1,000 Elements:

Now, let’s run the benchmark with an array size of 1,000 elements and wait for the result:

| Method | arraySize | Mean | Error | StdDev | Median |
|--------------------- |---------- |----------------:|--------------:|----------------:|----------------:|
| ArrayIndexInitializer| 1000 | 542.5 ns | 6.13 ns | 5.43 ns | 542.3 ns |
| ListCollection | 1000 | 2,151.2 ns | 42.14 ns | 64.36 ns | 2,141.9 ns |
| ArrayCopyTo | 1000 | 2,181.7 ns | 43.36 ns | 51.62 ns | 2,170.3 ns |
| LinqConcat | 1000 | 2,474.5 ns | 16.86 ns | 13.16 ns | 2,474.2 ns |
| SetValueMethod | 1000 | 14,316.8 ns | 268.95 ns | 251.57 ns | 14,356.2 ns |
| LinqAppend | 1000 | 172,341.2 ns | 3,399.26 ns | 8,402.14 ns | 168,804.7 ns |
|               Method | arraySize |            Mean |         Error |          StdDev |          Median |
|--------------------- |---------- |----------------:|--------------:|----------------:|----------------:|
| ArrayIndexInitializer|      1000 |        542.5 ns |       6.13 ns |         5.43 ns |        542.3 ns |
|       ListCollection |      1000 |      2,151.2 ns |      42.14 ns |        64.36 ns |      2,141.9 ns |
|          ArrayCopyTo |      1000 |      2,181.7 ns |      43.36 ns |        51.62 ns |      2,170.3 ns |
|           LinqConcat |      1000 |      2,474.5 ns |      16.86 ns |        13.16 ns |      2,474.2 ns |
|       SetValueMethod |      1000 |     14,316.8 ns |     268.95 ns |       251.57 ns |     14,356.2 ns |
|           LinqAppend |      1000 |    172,341.2 ns |   3,399.26 ns |     8,402.14 ns |    168,804.7 ns |

From the result, we can clearly see that the ArrayIndexInitializer approach is the fastest with a mean of 542.5 ns for an array size of 1,000.

And then, the ListCollection approach is ~4 times slower with a mean of 2,151.2 ns. The ArrayCopyTo approach is almost close to the ListCollection with a mean of 2,181.7 ns.

Surprisingly, the SetValueMethod approach is ~26 times slower than the index initializer approach with a mean of 14,316.8 ns.

The slowest of all approaches is the LinqAppend approach which is almost ~317 times slower than the index initializer approach. It clearly shows that this approach is not suitable when we want to append a large number of elements to an array.

Benchmark With 10,000 Elements

Now, let’s run the same benchmark for an array size of 10,000 and look for the result:

| Method | arraySize | Mean | Error | StdDev | Median |
|--------------------- |---------- |----------------:|--------------:|----------------:|----------------:|
| ArrayIndexInitializer| 10000 | 4,062.3 ns | 60.70 ns | 53.81 ns | 4,042.3 ns |
| LinqConcat | 10000 | 21,042.1 ns | 231.71 ns | 216.74 ns | 20,994.9 ns |
| ArrayCopyTo | 10000 | 22,281.6 ns | 440.88 ns | 900.61 ns | 22,648.8 ns |
| ListCollection | 10000 | 22,483.6 ns | 339.80 ns | 283.75 ns | 22,494.7 ns |
| SetValueMethod | 10000 | 149,466.5 ns | 2,852.33 ns | 7,951.17 ns | 146,255.6 ns |
| LinqAppend | 10000 | 14,526,846.5 ns | 416,189.86 ns | 1,180,661.37 ns | 14,136,703.1 ns |
|               Method | arraySize |            Mean |         Error |          StdDev |          Median |
|--------------------- |---------- |----------------:|--------------:|----------------:|----------------:|
| ArrayIndexInitializer|     10000 |      4,062.3 ns |      60.70 ns |        53.81 ns |      4,042.3 ns |
|           LinqConcat |     10000 |     21,042.1 ns |     231.71 ns |       216.74 ns |     20,994.9 ns |
|          ArrayCopyTo |     10000 |     22,281.6 ns |     440.88 ns |       900.61 ns |     22,648.8 ns | 
|       ListCollection |     10000 |     22,483.6 ns |     339.80 ns |       283.75 ns |     22,494.7 ns |
|       SetValueMethod |     10000 |    149,466.5 ns |   2,852.33 ns |     7,951.17 ns |    146,255.6 ns |
|           LinqAppend |     10000 | 14,526,846.5 ns | 416,189.86 ns | 1,180,661.37 ns | 14,136,703.1 ns |

We can see that the mean increases almost proportionately to the array size. We can also see that the LinqConcat approach performs better than ArrayCopyTo and ListCollection with the increase in size. ArrayIndexInitializer remains the winner of this benchmark.

Conclusion

In this article, we’ve learned how to add values to a C# array. Later, we compared the performance of the different approaches and finally came to know that the array index initialization is the fastest approach.

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Share:

Subscribe
guest
Label
2 Comments
Oldest
asp.net-core-web-api-best-practices-image.png

Get our free, easy Web API best practices guide
used by 20k+ people to become better web devs.

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2022

wpDiscuz


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK