Hi
Both codes gives 10 20 and 30. I'm just wondering which one is the best (efficient)? Thanks. V.
First way:
using System;
class X
{
static void Main(string[] args)
{
int[] s = new int[3];
s[0] = 1; s[1] = 2; s[2] = 3;
for (int i = 0; i < s.Length; i++)
Console.WriteLine(p(s,i)[i]);
}
static int[] p(int[] sl, int x)
{
sl[x] *= 10;
return sl;
}
}
Second way:
using System;
class X
{
static void Main(string[] args)
{
int[] s = new int[3];
int[] s2 = new int[3];
s[0] = 1; s[1] = 2; s[2] = 3;
s2 = p(s);
for (int i = 0; i < s.Length; i++)
Console.WriteLine(s2[i]);
}
static int[] p(int[] sl)
{
for (int i = 0; i < sl.Length; i++)
sl[i] *= 10;
return sl;
}
}
Anupam MaitiPosted Feb 5, 2023, 12:19 PM
The reason behind the second method is better in terms of code clarity and avoiding potential bugs as it does not modify the original array, but instead returns a new array with the desired values.
Anandu G NathPosted Dec 20, 2023, 5:26 AM
The second way (the method that directly modifies the array) is generally more efficient because:
The first way (the method that modifies a specific index and returns the array) involves more overhead due to the repeated method calls and array returns for each index modification.
Valerie MeunierPosted Feb 4, 2023, 3:57 PM
Thanks
Naimish MakwanaPosted Feb 4, 2023, 3:14 PM
Hello Valerie,
second way is more efficient as it modifies the values of the array in-place and returns the modified array. In the first way its creating a new copy of the array in each iteration of the loop.
So, the second way is more efficient.
Thanks
Naimish