Advertisement
wch1zpink

Fastlist Script Objects

Mar 23rd, 2021 (edited)
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. In theory, no matter how long the list is, the lookup time should be the same every time, but when we look at the results, we see that the time it takes to get the list item grows twice as large each time we double the size of the list—a linear increase, in other words, or O(n) efficiency. So if, for example, we were writing a script to loop over a variable number of items in a list, we would see the time it takes increase quadratically compared to the number of items in the list, or O(n*n). Ouch! That could really start to bite if you have, say, several thousand items to get through, perhaps even becoming the major performance bottleneck in your code.
  2. Fortunately, there is a “solution” of sorts that tricks AppleScript lists into performing constant-time lookups. If you wrap up your list in a script object property and refer to it there, something in the way that AppleScript references work causes whatever piece of the interpreter that is causing the slowdown to be bypassed.
  3.  
  4. As to exactly how and why this hack works, I have no idea; only an Apple engineer could tell you that. But on this occasion, I’m just glad it does. For example, if you have a large list you need to loop over, you can modify your code from this,
  5. repeat with i from 1 to length of some_list
  6. -- Do some stuff...
  7. set an_item to item i of some_list
  8. -- And more stuff...
  9. set item i of some_list to new_value
  10. -- And yet more stuff...
  11. end repeat
  12. to this:
  13. script FastList
  14. property fast_list : some_list
  15. end script
  16. repeat with i from 1 to length of FastList's fast_list
  17. -- Do some stuff...
  18. set an_item to item i of FastList's fast_list
  19. -- And more stuff...
  20. set item i of FastList's fast_list to new_value
  21. -- And yet more stuff...
  22. end repeat
  23.  
  24. CAUTION: Because the modified code uses a named script object, make sure you put it inside a handler. If you put it at the top level of your script, the AppleScript compiler will see the script statement and assume you want the script object created and assigned to the identifier FastList when the script is compiled...and promptly throw a compiler error because it cannot find the value of the some_list variable to assign to the object’s fast_list property. Putting the script statement inside a handler ensures it is only evaluated at the point at which it is needed.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement