Assigning a local var versus calling the getter each time

Logic says that assigning a local var for a control’s property is more efficient than calling the getter for the value over and over in a loop:

[code]Dim x As Integer
Dim lCount As Integer = lbTheList.LixtCount -1

for x = 0 To lCount
Do Something
next
[/code]
Versus

[code]Dim x As Integer

for x = 0 To lbTheList.ListCount - 1
Do Something
Next
[/code]
However, real tests on a listbox containing a few thousand entries is showing the same time used in each case.

Is the compiler turning the second entry into the first behind the scenes?

unlikely
I dont believe it implements any invariant code motion optimizations

how many rows have you got in this list ?

Maybe I’ve just not his a large enough loop …

Logic says that calling the getter and doing a sub on the return value should be recognizable at the microsecond level, but my tests are always within 1 or 2 microseconds over the entire run. Could that be because my “Do Something” (a 3 value mult) is getting squashed since the value is the same each loop iteration?

that would be my guess
here I did

listbox1.Visible = False
listbox1.SelectedRowIndex = -1

For i As Integer = 0 To 100000
  
  listbox1.AddRow Str(i)
  
Next

listbox1.Visible = False
listbox1.SelectedRowIndex = -1

If True Then
  Dim starttime As Double = System.Microseconds
  
  For i As Integer = 1 To 10
    
    For x As Integer = 0 To listbox1.ListCount - 1
      Dim s As String = listbox1.CellValueAt(x,0)
    Next
    
  Next
  
  Dim endtime As Double = System.Microseconds
  
  MsgBox " took " + Format(endtime-starttime,"#########.000")
  
End If

If True Then
  Dim starttime As Double = System.Microseconds
  
  For i As Integer = 1 To 10
    
    Dim lCount As Integer = listbox1.ListCount -1
    
    For x As Integer = 0 To lCount
      Dim s As String = listbox1.CellValueAt(x,0)
    Next
    
  Next
  
  Dim endtime As Double = System.Microseconds
  
  MsgBox " took " + Format(endtime-starttime,"#########.000")
  
End If

in debug the first one gives 187.5441.333
the second 1059555.842

when compiled they get much different

  1. 1782151.321
  2. 936432.461 (nearly 2x as fast)

Okay, local variable it is! I knew this didn’t feel right.

:S

yeah usually manually doint the kind of optimizations is right

it would be nice to know which optimizations the compiler does to (code motion, common subexpression elimination etc)
<https://xojo.com/issue/59746>