Documentation Center

Code optimization

Sax Basic is very flexible - there are usually several ways to accomplish the same task. When you are writing macros you will probably be happy enough to get one that does what is required; when writing one that will be used many times, or will be used by a group of users, you will probably want to ensure that the most efficient coding is used. The following techniques describe ways in which you can make your macros smaller and faster.

Minimizing OLE references

Every Sax Basic method or property call requires one or more OLE calls, each of which takes time. Minimize the number of such calls.

Use Object Variables

If you find you are using the same object reference many times, set a variable for the object and use that instead.

Use the With Statement

Use the With statement to avoid unnecessary repetition of object references without setting an explicit object variable.

Use a For-Each Loop

Using a For-Each loop to iterate through a collection or array is faster than using an indexed loop. In most cases it is also more convenient and makes your macro smaller and easier to debug.

Keeping Properties and Methods Outside Loops

Your code can get variable values faster than it can get property values. You should therefore assign a variable to the property of an object outside the loop and use that within a loop, rather than obtaining the property value each time within the loop. For example:

For i = 2 To 50
  srclst.String(i).Comment = srclst.String(1).Comment
Next counter

this is inefficient and should be replaced by:

Dim comment as string
comment = srclst.String(1).Comment 
For i = 2 To 50
  srclst.String(i).Comment = comment
Next counter

If you're using an object accessor inside a loop, try moving it outside the loop:

For i = 1 to 50
 PSL.ActiveSourceList.String(i).Comment = "Remark"
Next

should be replaced by:

With PSL.ActiveSourceList
For i = 1 To 50
  .String(i).Comment = "Remark"
Next i
End With

Using Collection Index Numbers

Most object accessor methods allow you to specify an individual object in a collection whether by name or by index number. Using the number is much faster than using the name. Set against this, however, is the fact that using the name makes your code easier to read, and will specify the object uniquely (the number could change).

Minimizing the Use of Variant Variables

Although you may find it convenient to use variant types in your code, it is a waste of storage and slower to process such variables. Declare your variables explicitly wherever possible.

Use Specific Object types

If you declare object variables with the Object generic type, Sax Basic may have to resolve their references at run-time; if you use the specific object declaration Sax Basic can resolve the reference at compile-time.

Use Constants

Using declared constants in an application makes it run faster, since it evaluates and stores the constant once when the code is compiled.