Discuss Scratch

potatokirk
Scratcher
11 posts

How efficient is the <[list] contains:> block?

<[ v] contains [thing] ?>
This one, does it simply go through every entry till it finds a match or is it better than that. I would be doing 100s of lookups per frame with this block and i want to know if it will slow my project
CST1229
Scratcher
1000+ posts

How efficient is the <[list] contains:> block?

it goes through every entry until it finds a match (but it DOES stop at the first one found so it's slightly faster if an entry exists early in the list)

same for “item # of () in list”

Last edited by CST1229 (Aug. 12, 2026 01:31:37)

nembence
Scratcher
1000+ posts

How efficient is the <[list] contains:> block?

Actually it goes through the list two times (once case-sensitive and once not)
It's still much faster than going through each item manually, because of the overhead of the Scratch interpreter
_nix
Scratcher
1000+ posts

How efficient is the <[list] contains:> block?

Depends how big the list is and what kind of data you're searching for. I prepared a list in two different ways:

delete all of [big list v]
repeat (10000)
add (pick random (1) to (100000)) to [big list v]
end

delete all of [big list v]
repeat (10000)
if <(pick random (1) to (2)) = [2]> then
add (join [a] (pick random (1) to (100000))) to [big list v]
else
add (join [A] (pick random (1) to (100000))) to [big list v]
end
end

Then I checked the list in two different ways:

reset timer
repeat until <(timer) > (1)>
if <[big list v] contains (pick random (1) to (1000000))> then
change [contains v] by (1)
else
change [doesn't contain v] by (1)
end
end
set [total runs v] to ((contains) + (doesn't contain))

...
if <[big list v] contains (join [a] (pick random (1) to (1000000)))> then :: stack
...

With strings in the list, I got around 1,400 runs in one second.
(around 20 contains + 1,390 doesn't contain)

With just numbers, I got around 11,000 runs in one second.
(around 100 contains + 10,900 doesn't contain)

With a list of 1000 strings (10x fewer), a/A + random 1 to 100000, I got 14,700 runs.
(around 150 contains + 14,500 doesn't contain)

With a list of 1000 numbers, random 1 to 100000, I got 106,000 runs.
(around 1000 contains + 105,000 doesn't contain)

Remember that these are measurements per second, not per frame, so you have to divide all the numbers by 30 to get your “frame bandwidth”:

10,000 strings: 1,400 / 30 = 45 per frame
10,000 numbers: 11,000 / 30 = 360 per frame
1,000 strings: 14,700 / 30 = 490 per frame
1,000 numbers: 106,000 / 30 = 3,500 per frame

I'm on a MacBook Air M2, which is a pretty speedy computer, running Safari (macOS 27 public beta). You can run the same kind of test on your computer to see what numbers you get. You might get a greater or lesser bandwidth.

Last edited by _nix (Aug. 12, 2026 14:07:30)

Powered by DjangoBB