following other programming languages' conventions i thought that maybe i should change my string constants to integer values to speed up the code. by that i mean that an object of mine has several states, so (self.)state has value "STRING1" or "STRING2" or etc. and i changed these so that i defined global STRING1=1, STRING2=2 etc. and used these. suprisingly the code became slower. making these constants local sped up the things, a bit faster than with strings, but still only approx. to the same speed as the string solution.
it is a bit surprising for me, and the conclusion is that in lua you don't need to optimize this (as many other things, e.g. sin tables).
summary:
constants vs local constants vs strings
pc:
2.1765020517934 vs 1.2641564022966 vs 1.2715337009151
android:
6.2562990000006 vs 4.3186989999958 vs 4.6480369999917
test code:
TOUCHED=1
RELEASED=2
something=TOUCHED
startTime=os.timer()
for i = 1, 10000000 do
if something==TOUCHED then something=RELEASED
elseif something==RELEASED then something=TOUCHED end
end
print(os.timer()-startTime)
local TOUCHED=1
local RELEASED=2
something=TOUCHED
startTime=os.timer()
for i = 1, 10000000 do
if something==TOUCHED then something=RELEASED
elseif something==RELEASED then something=TOUCHED end
end
print(os.timer()-startTime)
something="TOUCHED"
startTime=os.timer()
for i = 1, 10000000 do
if something=="TOUCHED" then something="RELEASED"
elseif something=="RELEASED" then something="TOUCHED" end
end
print(os.timer()-startTime) |
Comments
From types stand of point, then any variable can be any type and can change type, so in weakly typed languages in most cases, changing type won't give you a better performance, only may take less memory in some cases
i expected that checking the equality/setting value of strings will take significantly longer than checking the equality/setting the value of integers (even together with the lookup time of the global integer constants).
Fragmenter - animated loop machine and IKONOMIKON - the memory game
https://github.com/gideros/gideros
https://www.youtube.com/c/JohnBlackburn1975