In this article, we are going to explore how to print the elements of an array in C#. Also, we are going to compare these approaches to check which are the fastest and the slowest ones.
Let’s start it.
Preparing the Environment
Let’s create an array we want to print out and fill it with some elements:
private static readonly int[] _array = new int[] { 1, 4, 6, 7, 9, 3, 5 };
It is important to mention that some of our methods use System.Linq
namespace, and it is necessary to add the Linq namespace to our code if we are creating an application using .NET version earlier than 6.0:
using System.Linq;
Using For and Foreach Loops to Print the Elements of an Array
Let’s create a ForLoop
method to print out our elements:
public void ForLoop(int[] array) { for (int i = 0; i < array.Length; i++) { Console.Write($" ==> {array[i]}"); } }
As an input parameter, this method receives an array of int
. We iterate through this entire array, and for each index, we print the respective element at the console.
We can achieve the same result using the foreach
loop:
public void ForeachLoop(int[] array) { foreach (var item in array) { Console.Write($" ==> {item}"); } }
Using ForEach Method to Print the Elements of an Array
Let’s see how to print every element of the array using this technique:
public void ToListForEach(int[] array) { array.ToList().ForEach(element => Console.Write($" ==> {element}")); }
We receive an array as a parameter. Then, we create a new list using ToList()
method. After that, we use the built-in ForEach
method, under the List
class, to iterate over the array’s elements. We pass to the ForEach
method a lambda expression (element => Console.Write($" ==> {element})
) as a parameter. This lambda expression represents the Action Delegate
responsible to print each element.
Using String.Join to Print Out Array’s Elements
Another way to print array elements is using string.Join
:
Console.Write($" ==> { string.Join(" ==> ", _array)}");
We use the Console.Write
method to print all the elements. However, we have to provide those elements. This is where the Join
method comes into play. Its responsibility is to concatenate every element of the array (the second parameter) separating each with the string separator (first parameter).
Print Out Elements Using the Static Array Class
The static Array
class provides us with a method (ForEach
) to iterate through an array performing a specific operation. Let’s implement it:
Action<int> print = (element) => Console.Write($" ==> {element}"); Array.ForEach(_array, print);
First, we create an Action Delegate
responsible to print the elements on the screen. This Action
receives, as a parameter, the element we want to print out.
Secondly, we use the Array
class to call the ForEach
method. We pass the array we want to iterate through as a parameter and the Action
we defined.
It is good to mention that, if any of the parameters we send is null, the ForEach
method will throw an ArgumentNullException
.
Print Out Elements Using Span
Let’s create an AsSpan
method to print out the elements:
public void AsSpan(int[] array) { var span = array.AsSpan(); foreach (var item in span) { Console.Write($" ==> {item}"); } }
Here, we create a new instance of the Span
class based on the input parameter array. After that, we perform an iteration using a foreach
loop printing each element on the screen.
This AsSpan
method exists under the MemoryExtension
class.
Benchmark
Let’s implement a benchmark to compare these approaches, to find out which are the fastest and the slowest ones.
Let’s create a FillElements
method responsible to populate an array with 100 thousand elements:
private static int[] FillElements(int length) { var array = new int[length]; for (int i = 0; i < length; i++) { var value = new Random().Next(0, 1000); array[i] = value; } return array; }
Now, let’s check the benchmark results:
| Method | Mean | Error | StdDev | Median | |-------------- |--------:|---------:|---------:|--------:| | StringJoin | 1.106 s | 0.0640 s | 0.1730 s | 1.082 s | | AsSpan | 1.430 s | 0.0568 s | 0.1603 s | 1.293 s | | ToListForeach | 1.467 s | 0.1207 s | 0.3521 s | 1.279 s | | ForLoop | 1.488 s | 0.0873 s | 0.2476 s | 1.467 s | | ForeachLoop | 1.630 s | 0.1548 s | 0.4491 s | 1.686 s | | ArrayForEach | 1.790 s | 0.1093 s | 0.3118 s | 2.089 s |
Printing data on the screen is a heavy operation. That explains why all of our methods took more than 1 second to run.
The fastest approach is when we use the string.Join
(1.106 seconds). This method calls Console.Write
only once, passing all the elements we want to print as a string
.
Every other approach has a very similar efficiency, with just 0.360 seconds of difference when we compare the second-best (AsSpan
) with the slowest (ArrayForEach
) approach. We should also understand that, if we run this same benchmark many times, the order of these methods may change.
Conclusion
In this article, we have learned different ways to print the elements of an array using C#.
We have inspected a benchmark that showed us that, printing elements on the screen is a heavy operation and we need to be careful about how much data we want to print on the screen.
We have seen that all these approaches are very similar when we talk about efficiency, so, it is up to us to decide which one to use daily.