Apple Events

Apple events are expensive, and some Apple events are very expensive. You can't do anything about the time spent waiting for each Apple event to execute, but perhaps you can minimize the number of Apple events sent. At the same time, you may be able to improve the efficiency of the particular Apple events you do send.

The boolean expression at the top of a repeat while block must be evaluated before every repetition of the block, and then once more in order to decide not to repeat the block any further. This means that it should not contain any commands whose result will not change during the repetition, as it would be needless and wasteful overhead to issue those commands each time through the loop.

Here's a silly but telling example. Suppose we have two folders in the Finder, and we want to create enough new folders inside the first folder so that it contains the same number of items as the second folder. The following code expresses neatly and elegantly what we want done:

set x to 1
tell application "Finder"
    set f1 to folder "f1"
    set f2 to folder "f2"
    repeat while ((count items of f1) < (count items of f2))
        make new folder at f1 with properties {name:("f" & x)}
        set x to x + 1
    end repeat
end tell

But in the world of AppleScript, neat and elegant isn't always good. That code sends the count message to the Finder twice for each time through the loop, when in fact we need only send it twice at the outset as we prepare for the loop:

set x to 1 tell application "Finder" set ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.