Performance tweaks

In Xojo there are a number of things you can do to improve the performance of your code.

There are various pragmas you can enable that can improve speed – I’d suggest only doing this once you code is fully debugged and known to be working properly as turning these checks of can mean IF you have a bug your application just crashes hard.

And there are other things you can do like lifting out code that repeatedly does lookups in arrays.

So instead of

dim something(1000) as String

// intervening code to load data into the array

for i as integer = 0 to something.ubound

   if something(i) = "abc" then
   elseif something(i) = "def" then
   elseif something(i) = "ghi" then
   end if

you might rewrite this as

dim something(1000) as String

// intervening code to load data into the array

// 1) eliminate repeatedly accessing the Ubound property
dim maximumIndex as integer = something.ubound 

for i as integer = 0 to maximumIndex

   // 2) eliminate repeatedly doing an array access
   dim thisItem as string = something(i)

   if thisItem = "abc" then
   elseif thisItem = "def" then
   elseif thisItem = "ghi" then
   end if


It would be nice if the compiler could/would do more optimization of code. There are a host of optimizations that you could apply manually like common subexpression elimination and loop invariant code motion.

But sometimes the biggest performance wins are not from tweaks like these. Often applying a different algorithm has a much bigger bang for the buck than anything.

When I worked at Xojo there were a couple areas where simply by inverting how some data was accessed in memory the entire process was sped up enormously.

Databases will do this and may use the MOST selective index to retrieve data first so the initial set of data is very tiny, instead of starting with the most broad set of data, and then winnowing it down further. By doing this they can decrease the amount of memory required and the amount of data to iterate though to satisfy whatever query you’ve executed.

When you have a performance issue I would START by reconsidering how the data is accessed and used and whether you can alter the algorithm to gain an initial big speed up by doing things in a different order.

And once you get the algorithm working the way you want then apply all the other tweaks to code to squeeze the most out of it.

And JUST to be clear make sure you do timings in a COMPILED and BUILT version NOT aa debug version using RUN as a debug version still has a lot of debug related code in it that can influence the results and MAY mislead you.