Reputation: 448
I'm writing a very basic compiler for the .NET platform and would like to know something for my implementation of constants.
In my compiler, the use of constants will hopefully replace the ldloc operation.
If the constants theAge(18) and theName(Barry) were actually variables, the IL might be something like:
ldstr "Your name is "
ldloc theName
concat //Example operation for concatenating
ldstr " and you are "
concat
ldloc theAge
tostring //Example operation for changing the variable to a string
concat
But if I implemented constants:
ldstr "Your name is "
ldstr "Barry"
concat
ldstr " and you are "
concat
ldc.i4 18
tostring
concat
Which is faster: ldc.i4/ldstr or ldloc? Or is it better to store the constants as variables?
Upvotes: 0
Views: 147
Reputation: 244908
If I was to try to predict this (despite my own warning above), I would say that loading constants directly is going to be faster (if the difference is actually going to be measurable).
This is because in the ldc
option, the CPU will read the instruction and then can directly write the value to a register. With ldloc
, it will also load the value from the stack. The situation with ldstr
is similar.
But if the value in the local variable is effectively constant, the JIT compiler could optimize ldloc
to the same code as ldc
, so there might not be any difference at all. (But I don't know if the common JIT compilers can do that.)
Upvotes: 2