Matt Groth
Matt Groth

Reputation: 714

How to reduce overhead and run applescripts faster?

I'm developing an app that may have to run many applescripts in sequence, and I am looking for any way to run applescripts faster. I'm not talking about the internals, I'm talking just about the execution startup/cleanup.

Example:

onePlusOne.applescript:

1+1

I then compiled this with osacompile -o onePlusOne.scpt onePlusOne.applescript

Now, the test (in a bash shell):

time zsh -c "(( val = 1 + 1 ))":

real    0m0.013s
user    0m0.004s
sys 0m0.007s

time osascript onePlusOne.scpt:

real    0m0.054s
user    0m0.026s
sys 0m0.022s

I'm wondering if anything can be done about the additional overhead and to execute applescripts faster.

Upvotes: 1

Views: 365

Answers (1)

foo
foo

Reputation: 186

You don’t say what type of app, or what kind of AppleScripts, or whether the scripts are part of the app or user-supplied. Nor do you say if you’ve actually built a prototype and identified actual performance problems, or are talking purely hypotheticals at this point.

Assuming a typical sandboxed Swift/ObjC desktop app:

  • For arbitrary user-supplied AppleScripts, you usually want to use NSUserAppleScriptTask as that runs scripts outside the app’s own sandbox. One big limitation: its subprocesses aren’t persistent, so you can’t load a script once and call its handlers multiple times; you have to create a new subprocess each time, and if you want to preserve scripts’ state between calls then you’ll have to arrange something yourself.

  • Exception to the above: if your user-supplied scripts can run inside the limitations of your app’s sandbox then running them via NSAppleScript/OSAScript is an option, and those do allow you to load a script once and call it multiple times.

  • For built-in AppleScripts, use the AppleScript-ObjC bridge to expose your scripts as ObjC subclasses, and call their handlers directly. The overheads there are mostly in the time it takes to cross the bridge.

Otherwise, the overheads are the overheads; there’s usually not a lot you can do about them. TBH, your average AppleScript will spend more time waiting on IO (Apple event IPC is powerful but slow) or churning through pathological algorithms (e.g. iterating a list is generally O(n²) due to AS’s shonky internals, and most AppleScripters are amateurs so will write inefficient code). There may be ways to ameliorate poor runtime performance, but that is a far larger discussion.

One last consideration: with AppleScript-based automation, “Is it fast?” is less important than “Is it fast than doing the same task by hand”? And even a slow AppleScript will do a job 10–100x quicker than a fast human.

Upvotes: 3

Related Questions