[Edit: Hmmm… since writing this message, I retried the code that I thought was slow, realizing that I’d missed one extra use of “my” in front of “theTracks”, and that seems to be the real key to speed, not having the list pre-sized.
I’d still be curious about pre-sizing a list if possible, and I’m even more curious now about why the “my” keyword does the speed magic that it does.]
I’m wondering if there’s a way to automatically create a list with N items, sort of like declaring an array a[N] in another language. I wouldn’t really care if each item is a zero or an empty string or whatever.
Why?
I just discovered how changing all of the items in a long list is much, MUCH faster than building a new list by sequentially doing “set end of aList to…”.
For instance, this code to create a list which pairs each iTunes track with its database IDs:
tell application "iTunes"
set lib to library playlist 1
set tracksByID to every file track in lib
set trackCount to count tracksByID
set theIDs to database ID of every file track of lib
repeat with i from 1 to trackCount
set item i of my tracksByID to {item i of my theIDs, item i of my tracksByID}
--test
if i mod 100 = 0 then my reportProgress("" & i)
end repeat
-- blah, blah
end tell
…is much faster (especially with nearly 4000 songs in iTunes) than this code which I originally started with:
tell application "iTunes"
set lib to library playlist 1
set theTracks to every file track in lib
set trackCount to count theTracks
set theIDs to database ID of every file track of lib
set tracksByID to {}
repeat with i from 1 to trackCount
set end of my tracksByID to {item i of my theIDs, item i of my theTracks}
--test
if i mod 100 = 0 then my reportProgress("" & i)
end repeat
-- blah, blah
end tell
How much faster? From around 30 seconds down to less than one second.
It seems kind of silly for tracksByID to start out as a list of tracks without IDs, but the way I wrote the code was the easiest way I could see to make sure tracksByID was the right size for what I wanted to store in it. If I could have done something like “set count of tracksByID to trackCount” or ‘set tracksByID to “” repeated trackCount times’ – I would have done that.
Any way to get where I’m trying to go here?