Context
The context or environment from which a script is executed can make a huge difference to its speed. This is in large measure because Apple events are expensive. In particular, what makes them expensive is the context switch involved in communicating between one application and another. Thus it is typically fastest, where possible, to run a script from within the application it targets. If an application has a Script menu, therefore, it is worth putting the script there and executing it from there to see if this makes it faster.
(But also, there are some contexts that are inherently slower than others, for no discernable reason; it has something to do with how these contexts are programmed and that's that.)
Here's a test script:
set x to (get current date)
repeat 500 times
tell application "iTunes"
get name of it
end tell
end repeat
set y to (get current date)
set z to (y - x)
tell application "Finder"
activate
display dialog z
end tellTable 22-1 shows some rough timings on my machine for running that script from within various contexts.
Table 22-1. Timings for the same script executed in different contexts
|
Context |
Timing |
|---|---|
|
iTunes's Script Menu |
0.15 second |
|
Red Sweater FastScripts |
0.5 second |
|
Script Debugger |
1.5 seconds |
|
Apple's Script Menu |
8 seconds |
|
Script Editor |
9 seconds |
|
DragThing |
Timed out after 500 seconds |
Many external factors affect speed , so no absolute lessons can be drawn from a simple, unscientific test such as this; but clearly it can be worthwhile ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access