Android Question Const runtime behavior

Alessandro71

Well-Known Member
Licensed User
Longtime User
Please disregard the actual code, since it's just a proof of concept; the actual use case is way more elaborated but the core issue is the same
Does a Const variable, declared inside a loop, gets initialized at every loop iteration, or just once at program initialization (since it's a constant)?

B4X:
    For i = 0 To 1000
        Dim Const a() As Int = Array As Int(1, 2, 3, 4, 5)
        
        Log(a(1))
    Next

Here, the a() array is built and discarded 1000 times or just once?
 

MikeSW17

Active Member
Licensed User
Longtime User
A quick test I ran of your code, logging Ticks with the "Dim const" inside and outside the loop was:
Inside: 57 Ticks
Outside: 64 Ticks.

Doesn't exactly answer the question (@Erel did that), but supports his assertion of not much performance difference.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The difference between the two should be smaller.

B4X:
Dim Inside, Outside As Long
For x = 1 To 10
    Dim n As Long = DateTime.Now
    For i = 0 To 1000
        Dim Const a() As Int = Array As Int(1, 2, 3, 4, 5)
        Log(a(0))
    Next
    Inside = Inside + (DateTime.Now - n)
    
    Dim n As Long = DateTime.Now
    Dim Const a() As Int = Array As Int(1, 2, 3, 4, 5)
    For i = 0 To 1000
        Log(a(0))
    Next
    Outside = Outside + (DateTime.Now - n)
Next
Log(Inside / 10)
Log(Outside / 10)
I get 28ms for both of them.

Make sure to test in release mode.

The conclusion is correct, you don't need to worry about such things. There will be no real difference.
 
Upvote 0

Alessandro71

Well-Known Member
Licensed User
Longtime User
that code was just a proof of concept, the actual one is way more convoluted, with a Const Map initialization
my initial question could be translated as "since Const is a constant value, is it created one-time only through the program lifecycle, or is it created at declaration time, even if used multiple times?"
i understand the answer is "there is no optimization applied, it's created every time, but you should not worry about it", and that's fine for me
someone may also wonder the need for such a question: in my case, it's for code readabilty, keeping constants near the code where it is used, instead of moving them in some global place, but way out of sight.
 
Upvote 0
Top