find string in array

I am just wondering which code is faster??

the first one is using ‘indexof’

   Dim x as Integer
    x = gStockIDLine.IndexOf(gCurrStock)
    IF x>=0 then
      vCurr=x
      DoGetStockOneRecord(vCurr,false)
    END IF

the second one comparing the gCurrStock string with the value in the array looping using for next loop.

   DIM x AS integer
    for x= 0 to ubound(gStockIDLine)
      if gStockIDLine(x)= gCurrStock then
        vCurr=x
        DoGetStockOneRecord(vCurr,false)
      END IF
    next x

They’re not equivalent. The first will only call DoGetStockOneRecord for the first item that matches. The second will call it for all items that match.

If you timed these with large enough arrays of unique elements, you might expect to find the first to be faster because the IndexOf function might not yield to other threads as it loops. You might match performance with the second by using a #pragma DisableBackgroundTasks.

thanks brad… i don’t need to call DoGetStockOneRecord for all matching records. Do i need to use #pragma DisableBackgroundTasks on the first code??

#pragma DisableBackgroundTasks wouldn’t effect methods you call, such as IndexOf, so no, you don’t need it there.

so i should use #pragma DisableBackgroundTasks only if i need to do looping eg for next loop or while wend?

Actually, you should use it sparingly, only in cases where performance is absolutely critical. Using it will prevent Xojo from doing things in the background like yielding time to another thread or updating the UI. If your code is long enough, the user will get a spinning wheel too. Frankly, Xojo is fast enough that you won’t even notice a difference in normal operations.

In your specific case, I’d use IndexOf. If gStockIDLine is expected to get very large, consider using a Dictionary instead of an array.