Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: Nested ForEach [closed]

Is there a best practice for the number of nested "foreach"?

That is I'm spiraling into nested "foreach" over Complex dictionaries, is there a point where it starts to produce overhead that "COULD" impede performance? Is this something even worth considering.

To make it specific and not open to being subjective: I have 3 Complex Dictionaries that look like this;

Dictionary<int, Dictionary<string, XObject>()
Dictionary<string, List<YObject>()
Dictionary<string, Dictionary<string, List<ZObjects>()

Obviously now, as I filter these Dictionary (in a foreach), to produce the data I'm looking for, the structure of my code is heading towards 5 Nested "foreach" excluding the Outer 1. In answering these are the areas I'm worried might be impacted:

  1. Performance (too many context switches)
  2. Memory (retaining all the datasets in memory at a given instant)
  3. Maintainability (bad programmer!)

Best practice or doesn't matter?

like image 218
Dane Balia Avatar asked Aug 30 '26 09:08

Dane Balia


1 Answers

  1. There is no "context switch" for a foreach statement.
  2. Memory: quite irrelevant, the memory is taken by data not by Enumerators (used by foreach statements)
  3. Maintanability: Consider refactoring your code adding methods to perform items
like image 129
Stefano Altieri Avatar answered Sep 01 '26 09:09

Stefano Altieri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!