Inspection Option Suggestion - Possible multiple enumeration of IEnumerable

I have a suggested addition to the Possible multiple enumeration of IEnumerable inspection option in ReSharper.  ReSharper can understand the possible multiple enumeration when you explicitly access an IEnumerable twice, such as in the example on http://confluence.jetbrains.com/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable:

IEnumerable<string> names = GetNames();

foreach (var name in names)

  Console.WriteLine("Found " + name);

var allNames = new StringBuilder();

foreach (var name in names)

  allNames.Append(name + " ");


However, ReSharper misses the case when you use an IEnumerable inside a LINQ statement.  As an example:

IEnumerable<Employee> employees = GetEmployees();

IEnumerable<Team> teams = GetTeams().Where(t => t.Enabled);
return employees.Where(e => teams.Any(t => t.TeamID == e.TeamID && t.Name == "Engineering"));


ReSharper 8.2.2 doesn't give an inspection notification to me for this code.  But in this case, for every employee, we filter on enabled teams.  Adding a ToList() or .ToArray() to the end of the 2nd line may dramatically speed up this code block.

I have spent countless hours dealing with these cases, trying to speed up my code and I think it would help if ReSharper found this for me.

Thanks.
Steve

1
2 comments

I agree with Steve and the curent version of Resharper(2021.3.3) seems to still have same restriciton.

For example,

1        public void Exec(IEnumerable<string> enumSource1)
2        {
3            var enumSource2 = GetEnum();
4            var var1 = enumSource1.Any(e => e == enumSource2.SingleOrDefault());
5            var var2 = enumSource1.Where(e => e == enumSource2.First());
6        }

The code "enumSource1.Any" on the line #4 increases the use count of  IEnumerable(enumSource1), and it seems that the inspector reacts with both of enumSource1 on the line #4 and #5 to report "Possible multiple enumeration of IEnumerable".

However, the inspector doesn't react with "enumSource2" on the line #4 and #5 because they are in lambda expressions.

I suppose performance problems are often and easily made in lambda expressions, so I also expect the inspection option as Steve does.

0

Hi sadap

Thank you for the suggestion. We already have a feature request for this case: RSRP-337057. As you can notice, this request is now in the Shelved state. That means we don't have plans for it in the foreseeable future. However, you can upvote/comment on it to bring some attention to this case. 

Have a great day! 

0

Please sign in to leave a comment.