[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Looping through an array with FOR EACH


Le 16/01/2026 à 00:21, Gianluigi a écrit :

Dear Benoit,

I apologize for creating all this confusion.

It all started with a forum user writing that it would have been better to loop through the array with For Each.
Then I remembered your warning (which, as usual, I misunderstood).

But at this point, you need to explain to me why the FOR EACH loop would be better than the one I suggested:

[code] Public Sub Main()

   Dim aAreas As New String[][] ' The dynamic matrix
   Dim r, c, e, i As Integer
   ' Array of support to the random filling of the matrix with pseudo names
  Dim aNomi As String[] = ["Ful", "Gal", "Doc", "Ech", "All", "Bil", "Val", "Mal", "Cec", "Lol", "Nib"]

   r = 5 ' six rows
   ' Initializes the random number generator
   Randomize
   ' Loop to populate the dynamic array
   For e = 0 To r
     ' Resize the array
     aAreas.Resize(e + 1)
     ' Instantiates a new internal array
     aAreas[e] = New String[]
     ' random number of columns
     c = Rand(0, 8)
     ' Loop to populate the array
     For i = 0 To c
       ' Resize the array
       aAreas[e].Resize(i + 1)
      ' Generate random names, but with number of row and column for the control        aAreas[e][i] = aNomi[Rand(0, 10)] & "(C" & CStr(i + 1) & " R" & CStr(e + 1) & ")"
     Next
   Next
   ' Read the jagged matrix
   For r = 0 To aAreas.Max
     For c = 0 To aAreas[r].Max
       Print aAreas[r][c];;
     Next
     Print
   Next

   ' This may be better <----------------------???
   Print "=============================================================="
   For Each area As String[] In aAreas
         For Each entry As String In area
             Print entry;;
         Next
         Print
     Next

End [/code]

With Best Regards
Gianluigi



Better for what?

"For Each" on an array is usually slower than using a "For...To" loop with an index variable, except if you don't need the index. Check by yourself anyway according to what you need exactly.

And the JIT compiler do not optimize the "For Each" loop.

Otherwise it's not important how you browse the array.

Regards,

--
Benoît Minisini.


Follow-Ups:
Re: Looping through an array with FOR EACHGianluigi <gradobag@xxxxxxxxxxx>
References:
Looping through an array with FOR EACHGianluigi <gradobag@xxxxxxxxxxx>
Re: Looping through an array with FOR EACHBB <adamnt42@xxxxxxxxx>
Re: Looping through an array with FOR EACHGianluigi <gradobag@xxxxxxxxxxx>
Re: Looping through an array with FOR EACHBrian G <brian@xxxxxxxxxxxxxxxx>
Re: Looping through an array with FOR EACHGianluigi <gradobag@xxxxxxxxxxx>
Re: Looping through an array with FOR EACHBenoît Minisini <benoit.minisini@xxxxxxxxxxxxxxxx>
Re: Looping through an array with FOR EACHGianluigi <gradobag@xxxxxxxxxxx>