0

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Barry
  • 448
  • 5
  • 10
  • 2
    Worrying about such details during initial development is premature, IMHO. Once you have a compiler that actually works in every respect you can go back and experiment with alternative code generation sequences and make changes if you think they are justified. – 500 - Internal Server Error Nov 05 '15 at 11:45
  • Hmm, you are skipping essential stuff, before you can use LDLOC you first have to initialize the variable. Perhaps with LDSTR. There is only a weak link between MSIL and the machine code that *actually* runs on the processor but a very basic rough measure is that more MSIL takes more time to execute. If the variable was in fact initialized with LDSTR then it doesn't matter, the jitter optimizer trivially removes it. – Hans Passant Nov 05 '15 at 15:12

1 Answers1

2
  1. I agree with @500's comment: this is a microoptimization, you should worry about this only after your compiler is working. And then, you should use benchmarks to figure out which options is faster and by how much, performance is notoriously hard to predict.
  2. 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.)

svick
  • 236,525
  • 50
  • 385
  • 514