Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 05:36 24 Nov 2025 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : MMBasic subroutine performance tips

Author Message
matherp
Guru

Joined: 11/12/2012
Location: United Kingdom
Posts: 10642
Posted: 09:58am 23 Nov 2025
Copy link to clipboard 
Print this post

To optimise performance do not use the same name for local variables in nested subroutines.
Variables are created in a hash table. So by definition if you use i as an index in a subroutine called by a subroutine that also uses i. There will have been a hash table collision that the firmware resolves by looking for the next free slot. This is completely benign but does take extra time: not a lot but some.

Also, it is very slightly quicker if variables are typed at declaration rather than being typed with a suffix

Demo 1
fred
'
Sub fred
 Local i%=22,ii%=23
 bert
 Print i%,ii%
End Sub
'
Sub bert
 Local i%,j%,ii%,jj%
 Timer =0
 For i%=1 To 100000
 ii%=i%
 Next
 Print Timer
 Timer =0
 For j%=1 To 100000
 jj%=j%
 Next
Print Timer
End Sub

Demo2
Option explicit
Option default integer
fred
'
Sub fred
 Local i=22,ii=23
 bert
 Print i,ii
End Sub
'
Sub bert
 Local i,j,ii,jj
 Timer =0
 For i=1 To 100000
 ii=i
 Next
 Print Timer
 Timer =0
 For j=1 To 100000
 jj=j
 Next
Print Timer
End Sub
 
LeoNicolas

Guru

Joined: 07/10/2020
Location: Canada
Posts: 541
Posted: 10:37am 23 Nov 2025
Copy link to clipboard 
Print this post

Thank you for the tip

That makes sense. Hash tables have an O(1) time access for the best scenario, and O(N) for the worst case, when keys collide. It is still possible to have a key collision even with keys with different names, if both strings have the same hash, but the chance to happen is very low.

Is it possible to store the local variable in the hash table using a composite key consisting of the method name + variable name? This should solve the issue.
 
Print this page


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2025