Android Question Constant Expression Calculation

rgarnett1955

Active Member
Licensed User
Longtime User
Hi,

If I enter the following code does the compiler calculate the constant expressions at compilation time?

Example Mathematical Expression:
    jdMinutes = Floor(Floor(jdTimeOnly * 24 * 60) / 5) * 5 *  24 * 60

i.e does 24 * 60 get calc'd at compile time and replaced with 1440 or does it just produce executable code that does the calc (24 * 60) when the code is run?

I am assuming the former for now as most compilers do this.

Best regards
Rob
 

rgarnett1955

Active Member
Licensed User
Longtime User
Hi Oparra,

I don't think I explained myself properly. I am not asking about evaluating string expressions in variables, I am asking whether the B4J/java compiler evaluates constant. expressions in statements.

Most compilers do this:

Thus the machine code translated for the statement for a variable multiplied by two constants eg.

fredvar = var * 24 * 60 => gets executed as fredVar = var * 1440

The compiler does the calc 24 * 60 and the machine code is populated with a single var 1440. of the correct type.

I suspect the B4J/java compiler does this, I just want to be sure. If it doesn't do this then to speed things up it would be best to writie the statement as:

fredVar = var * 1440

It doesn't matter a lot unless the calc is done many times in a loop.

Best regards
Rob
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
As I understand it, the sequence of interpretation of a formula is the use of parentisis "( )".

If the compiler does not detect parentisis, it will follow the normal mathematical interpretation.

And without the use of these, you can produce fluctuations in the expected results.

jdMinutes = Floor(Floor(jdTimeOnly * 24 * 60) / 5) * 5 * 24 * 60
 
Upvote 0

rgarnett1955

Active Member
Licensed User
Longtime User
Hi

I understand that the parenthisis will effect the calc order. So what you are saying is the compiler precalc constant expressions at compile time?


Best regards
Rob
 
Upvote 0

kimstudio

Active Member
Licensed User
Longtime User
In project directory you will find the converted java source from B4A (objects/src).
After compiled to class, use jd-gui.exe to decompile the class to src.
I just checked using your code and found none of them do the precalc constant expressions.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The correct answer is: it doesn't matter. Your code will run so fast that you don't need to worry about such things.
If your code is not fast enough then the solution will never come from such insignificant things.

I just checked using your code and found none of them do the precalc constant expressions.
Not accurate.
The JVM is very sophisticated and it does many optimizations in different levels.

Watch the preoptimization video tutorial. It is very important.
 
Upvote 0
Top