I was wondering which block was more optimal to use in a case where you want to iterate for a length of a list. For example:
Should you use something like this:
Or this:
I do not need to use the item variable in my loop. Is there an objectively better block or is to just personal preference? I am currently leaning towards repeat(lengthOf(list)) because it seems more straightforward to me, but I am open to suggestions. Thanks!
If you don’t need the contents of the list, it’s probably better to use repeat ([length V] of (list)) {
} . If you want the indexes, you may want to use for ((i)) = (1) to ([length V] of (list)) {
}
Both for (i) = () to () and for each (item) in () create variables which you don’t need for this situation. You might want a little bit of performance, even though the difference is not discernible.
Depending on how the list was created, Snap! probably knows the length of the list without walking through each item. But any efficiency difference will be small, because you want to repeat the DOsOMETHING that many times anyway. If you’re really worried about running time, see if you can find a way to avoid the repetition altogether. For a simple example of what I mean, instead of
In terms of the control structure itself: repeat vs for vs for each do not have any meaningful differences in performance. Whether or not an additional variable is created to reference each item or an index won’t affect anything.
what’s best depends on your use, but in this case we would generally say less is more. If you don’t need an index you should use a basic repeat loop because it avoids the question of “why wasn’t an index used”.
code is read way more often than it is written. Clarity is always a valid goal.