先日、AppleScript のリストの高速化についてまとめた記事を更新した。その高速化手法を全面的に採用したライブラリが XList です。
リストの高速化手法をザックリと言ってしまえば、script object の property を経由してリストの要素にアクセスすると、速いよ!ということです。しかし、property にアクセスというのはライブラリ化の際にはご法度です。ライブラリのインターフェースはメソッドで統一するのが常道です。つまり、property に直接アクセスせず、ハンドラの呼び出しで全てを行うようにします。
このため、XList を使ったループ処理は property に直接アクセするよりは、ちょっと遅くなります。それでも、十二分に高速です。
XList はいくつかの方法でのループを提供していますが、一番のオススメは block script および each を使った方法です。柔軟性と速度のバランスが良いと思っています。
以下、XList および、一般的な方法、リストを property 経由でアクセスする方法の速度の比較です。詳細は、コード中のコメントに頑張って書いてあります。
use LapTime : script "LapTime"
use XList : script "XList"
on main()
set a_list to {}
repeat with n from 1 to 10000
set end of a_list to n
end repeat
set tm to LapTime's start_timer()
repeat with an_item in a_list
get contents of an_item
end repeat
tm's duration()
set tm to LapTime's start_timer()
script list_wrapper
property cnts : a_list
end script
repeat with an_item in cnts of list_wrapper
get contents of an_item
end repeat
tm's duration()
set x_list to XList's make_with(a_list)
script block
on do(x)
return x
end do
end script
set tm to LapTime's start_timer()
x_list's each(block)
tm's duration()
set tm to LapTime's start_timer()
x_list's each_rush(block)
tm's duration()
set tm to LapTime's start_timer()
tell x_list
repeat while its has_next()
its next()
end repeat
end tell
tm's duration()
set tm to LapTime's start_timer()
script block2
on do(x)
return x * 2
end do
end script
set new_list to x_list's map(block2)
tm's duration()
set tm to LapTime's start_timer()
set new_list to {}
repeat with an_item in cnts of list_wrapper
set end of new_list to (an_item * 2)
end repeat
tm's duration()
end main
main()