2013-04-01 218 views
5

AppleScript的文檔建議將以下代碼有效地建立一個列表:如何在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 

的使用注意事項中明確提到的。這個工作在一個腳本或一個明確的運行處理程序中的頂級精品,但如果你像這樣逐字另一個處理程序中運行完全相同的代碼:

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() 

它打破,產生一個錯誤消息說,「燦不要將bigList轉換爲類型引用。「爲什麼這會中斷,以及在run()以外的處理程序中有效地構建列表的正確方法是什麼?

+1

這裏遇到了同樣的問題(沒有滿意的答案):http://stackoverflow.com/questions/3569847/why-cant-applescript-make-firstvalue-of-hash-into-type-reference-in-this -test-c?rq = 1 – 108

+0

更有幫助的是這個:http://stackoverflow.com/questions/15777321/why-in-applescript-cant-you-declare-references-to-variables-local-to-handlers – 108

回答

1

set end of l to i似乎快於copy i to end of l

on f() 
    set l to {} 
    repeat with i from 1 to 100000 
     set end of l to i 
    end repeat 
    l 
end f 
set t to time of (current date) 
set l to f() 
(time of (current date)) - t 

你也可以使用腳本對象:

on f() 
    script s 
     property l : {} 
    end script 
    repeat with i from 1 to 100000 
     copy i to end of l of s 
    end repeat 
    l of s 
end f 
set t to time of (current date) 
set l to f() 
(time of (current date)) - t 

100000也是在limit of items that can be saved in compiled scripts,所以你會得到這樣的錯誤如果您運行該腳本並嘗試將其保存爲scpt:

文檔「無標題」無法保存爲「Untitled.scpt」。

您可以把set l to f()一個處理器中,從而l爲本地,加set l to {}到年底,或腳本保存爲.applescript。

1

下面是我剛纔做的速度測試的結果和方法。請注意,每個試驗中的第一個結果比較慢,因爲該腳本之前沒有編譯過。

list_speed.xlsx

1

加入 「全球bigList」 到buildList的第一行()修復了編譯器錯誤。看起來,在運行處理程序中,默認情況下,變量是裸體的,並且對「運算符」的引用是有用的。但是,在其他上下文中,變量已經基本上是間接引用,並且創建另一個引用層會打破某些東西。在這些上下文中聲明一個全局變量剝去間接引用並允許「引用」操作符工作,但這不是必需的。只需使用默認的間接引用即可。

如果這不清楚,那是因爲我沒有完全理解這個機制。如果您對這裏發生的事情有更好的瞭解,請在下面評論。

相關問題