22.5. ContextThe 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 tell Table 22-1 shows some rough timings on my machine for running that script from within various contexts.
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 to consider the context in which a script will run when evaluating its speed. |