Compile AppleScript for Performance

Published | Go Back

Recently, I’ve found that com­pil­ing an AppleScript file may help with its per­for­mance.

I have this ar­guably weird work­flow on a Mac where I can press Command+2 and Command+3 to switch to spe­cific ap­pli­ca­tions. I did­n’t find any open source so­lu­tion for it, so I had to cre­ate some cus­tom AppleScripts and bind them to global hotkeys in Karabiner-Elements. The setup worked for me un­til I up­graded to ma­cOS Catalina, where the per­for­mance of the scripts was no­tice­ably de­graded. I had to wait for a few sec­onds be­fore the ap­pli­ca­tion switch­ing to the fore­ground.

I have to use the com­mand osascript to run my cus­tom AppleScript when the des­ig­nated hotkey is trig­gered. I was read­ing its man­ual for some in­spi­ra­tions, and I ac­tu­ally found one at the bot­tom of the man page: osacompile, which can com­pile AppleScripts. I gave it a try us­ing osacompile -x which is said to save the re­sult­ing script as ex­e­cute only. It did­n’t let me down. The ex­e­cu­tion per­for­mance of my script was im­proved dras­ti­cally.

This is not the end of the story though. I’ve no­ticed that al­though the per­for­mance is im­proved in gen­eral, it does­n’t elim­i­nate the prob­lem. Sometimes I still have to wait for a while for the script to fin­ish. My guess is that some­thing about AppleScript is changed in ma­cOS Catalina, like the script in­ter­pre­tor or the built-in script func­tions. Maybe some­thing about in­ter­cept­ing key­board in­puts is also changed so that Karabiner-Elements is slowed down.

That said, the gen­eral idea here may be help­ful in cer­tain cases. Maybe the next time when I’m deal­ing with scripts, I’ll re­mem­ber to check if there is a way to com­pile them.