I am just getting the days of the week back from the function. If it is a holiday week then just adding word 'holiday' after each day.
public IEnumerable<string> GetDays(bool isHolidayWeek)
{
var days= new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
var i = 0;
if (isHolidayWeek)
foreach (var day in days)
days[i++] = day + " Holiday";
return days;
}
so can this be written in a more efficient way? Perhaps using yield return?
You can use Select
method from System.Linq
to simplify your code and return a day names with Holiday
added (when isHolidayWeek
equals true
). Moving the Days
collection outside the method can also help to minimize a memory consumption (at little bit)
public static readonly IList<string> Days = new List<string>()
{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
public static IEnumerable<string> GetDays(bool isHolidayWeek)
{
if (isHolidayWeek)
return Days.Select(d => $"{d} Holiday");
return Days;
}
The problem here is that there is no need at all to new up an array everytime you call this method, it's an unnecessary waste of resources. What is going to change in
days
between calls?Moving
days
outside is easyThanks Pavel for the anwer. Newing up such a small array is not a big deal, we are living in 2020, not in 1980s, where you have to very cautious of your memory. I will keep the array in the function as it belongs/relate to this function only. Cheers
Of course its easy, but that is the main optimization, not using linq, and it was missing in your original answer. Linq as a matter of fact is probably a deoptimization for such a simpe scenario.
Also, why projection? Now you are projecting the same thing over and over again. Why not simply create the array with the holiday literals to begin with.