Speed tip with popupmenus

In a different forum a user reminded me of a speed tip that had cropped up once or twice over the years. It has to do with popupmenus.

Basically on older versions of macOS if you did


PopupMenu1.ListIndex = -1
For i As Integer = 0 To 1000
  PopupMenu1.AddRow Str(i)
Next

This behaved not so badly although there is a slightly faster variation

But on Mojave this is noticeably slow. This simple loop could take as much as a second on Mojave in dark mode.

To speed it up it was discovered that if you added an item in position(0), set the listindex to 0 then added all the items and removed that extraneous item at position 0 then the speed was hardly impacted at all.

PopupMenu2.AddRow ""
PopupMenu2.ListIndex = 0
For i As Integer = 0 To 1000
  PopupMenu2.AddRow Str(i)
Next
PopupMenu2.RemoveRow 0

My testing on 10.12.6 and 10.14.5, in light and dark modes, using 2019r1.1 with the following code shows the differences in the debugger

Sub Action()
  Dim startTime1 As Double 
  Dim endTime1 As Double
  
  Dim startTime2 As Double 
  Dim endTime2 As Double
  
  
  startTime1 = Microseconds
  PopupMenu1.ListIndex = -1
  For i As Integer = 0 To 1000
    PopupMenu1.AddRow Str(i)
  Next
  endTime1 = Microseconds
  
  
  startTime2 = Microseconds
  PopupMenu2.AddRow ""
  PopupMenu2.ListIndex = 0
  For i As Integer = 0 To 1000
    PopupMenu2.AddRow Str(i)
  Next
  PopupMenu2.RemoveRow 0
  endTime2 = Microseconds
  
  
  Dim total1 As Double = (endtime1 - startTime1) / 1000000
  Dim total2 As Double = (endtime2 - startTime2) / 1000000
  
  label1.text = str(total1, "###.00000")
  label2.text = str(total2, "###.00000")

End Sub

And the results are surprising and consistent between running in the debugger & a built application

Debug              Total1 (slow)       Total2 (fast)
 10.12.6            0.037 sec            0.012 sec
 10.14.5 (light)    1.152 sec            0.019 sec
 10.14.5 (dark)     1.158 sec            0.019 sec 
 Built x86_64       Total1 (slow)       Total2 (fast)
 10.12.6            0.036 sec            0.010 sec
 10.14.5 (light)    1.174 sec            0.017 sec
 10.14.5 (dark)     1.174 sec            0.028 sec

Whatever changed in Mojave Popupmenus got very slow.

Heads up.

Thanks to Jim McKay for reporting this