如何在AppleScript中的处理程序中有效地构建列表?

jri*_*rdo 5 performance applescript reference list handler

AppleScript文档建议以下代码有效地构建列表:

set bigList to {}
set bigListRef to a reference to bigList
set numItems to 100000
set t to (time of (current date)) --Start timing operations
repeat with n from 1 to numItems
    copy n to the end of bigListRef
end
set total to (time of (current date)) - t --End timing
Run Code Online (Sandbox Code Playgroud)

注意使用显式引用.这在脚本的顶级或显式运行处理程序中工作正常,但如果您在另一个处理程序中逐字运行相同的完全代码,如下所示:

on buildList()
    set bigList to {}
    set bigListRef to a reference to bigList
    set numItems to 100000
    set t to (time of (current date)) --Start timing operations
    repeat with n from 1 to numItems
        copy n to the end of bigListRef
    end
    set total to (time of (current date)) - t --End timing
end buildList
buildList()
Run Code Online (Sandbox Code Playgroud)

它打破了,产生一条错误消息,说"不能将bigList变成类型引用".为什么这会破坏,在run()之外的处理程序中有效构建列表的正确方法是什么?

Lri*_*Lri 1

set end of l to i似乎比copy i to end of l

\n\n
on f()\n    set l to {}\n    repeat with i from 1 to 100000\n        set end of l to i\n    end repeat\n    l\nend f\nset t to time of (current date)\nset l to f()\n(time of (current date)) - t\n
Run Code Online (Sandbox Code Playgroud)\n\n

您还可以使用脚本对象:

\n\n
on f()\n    script s\n        property l : {}\n    end script\n    repeat with i from 1 to 100000\n        copy i to end of l of s\n    end repeat\n    l of s\nend f\nset t to time of (current date)\nset l to f()\n(time of (current date)) - t\n
Run Code Online (Sandbox Code Playgroud)\n\n

100000 也超出了可保存在已编译脚本中的项目限制,因此如果运行脚本并尝试将其另存为 scpt,您将收到如下错误:

\n\n
\n

文档 \xe2\x80\x9cUntitled\xe2\x80\x9d 无法保存为 \xe2\x80\x9cUntitled.scpt\xe2\x80\x9d。

\n
\n\n

您可以将set l to f()其放入处理程序中,以便 l 是本地的,添加set l to {}到末尾,或者将脚本保存为 .applescript。

\n