LoginLogin

Optimizing Expressions

Root / Submissions / [.]

12Me21Created:
SmileBASIC will automatically optimize parts of expressions that use numerical constants and operators. This means you can write code like this:
FOR I=0 TO 16-1 ...
'and it won't be any slower than:
FOR I=0 TO 15 ...
Note that SB will not use mathematical simplification. For example:
X*2*3
'will not simplify to
X*6
To make SB simplify it, the multiplication of 2*3 must be done first, either X*(2*3) or 2*3*X Logical and comparison operators are not simplified (&& || > < >= <= == !=), nor are any string operations (string+string, string*number).

Important update!

It seems that during these optimizations, SB will convert all values into floats, do the operations, and then convert them back into integers if possible. This is different from how operations are normally done. For example, / will always do floating point division. The output will never be an integer, even if you do something like
X%=7
PRINT TYPEOF(X%/1)
However, during precompilation, 7/1 will actually become an integer, because the result is 7.0 (which can be converted to an integer). Certain operators that allow integer input will actually work differently during runtime:
X%=2147483647
PRINT 2147483647*2 '4294967294
PRINT X%*2 '-2
PRINT 2147483647+1 '2147483648
PRINT X%+1 '-2147483648
(This was discovered by SquareFingers and Calc84Maniac (https://smilebasicsource.com/forum?ftid=101) a long time ago but I completely forgot about it)

What about functions like SQR(2) or POW(5,4)?

Replying to:MZ952
What about functions like SQR(2) or POW(5,4)?
Unfortunately, no.