? faster FOR loop ● SmileBASIC Source

Sign In

*Usernames are case-sensitive
Forgot my password

faster FOR loop

Often people use something like FOR I=0 TO LEN(ARRAY)-1 to loop through an array, but this isn't optimal since it checks the length on each pass through the loop. A simple fix is to do: VAR L=LEN(ARRAY)-1:FOR I=0 TO L, but there is a better way: FOR I=LEN(ARRAY)-1 TO 0 STEP -1. This will only check the length once, and it doesn't have to set an extra variable. It will loop backwards, but that's fine if you're making an uppercase conversion function or something.
4 votes
3 Comment(s) randomous randomous Owner Robot Hidden Easter Eggs Second Year My account is over 2 years old Website Drawing I like to draw! Hobbies I thought step -1 was actually really slow. Like... it actually runs twice as slow as a regular empty for loop or something. Or was that PTC? 12Me21 12Me21 Admin Syntax Highlighter Received for creating the code syntax highlighter on SBS Night Person I like the quiet night and sleep late. Express Yourself Second Year My account is over 2 years old Website I think it's about the same speed as normal. Simeon Simeon Scholar Received for knowing a great deal about programming topics Achievements Amazing Page Hidden Achievements Drawing I like to draw! Hobbies Yeah, I've thought about that But I'm sure LEN(ARRAY) only fetches a quick value, no real computations are done, so the changes would be negligible But, when a for loop has a huge number of iterations to do, function calls can be a lot more computationally expensive (from experience) so this would be a smart trick to consider.