I'd like to know how does .maxstack really work. I know it doesn't have to do with the actual size of the types you are declaring but with the number of them. My questions are:
- does this apply just for the function, or to all the functions that we are calling for?
- even if it's just for the function were .maxstack is being declared, how do you know what maxstack is if you have branching? You go and see all the "paths" and return the maximum value possible?
- What happens if I set it to 16 and actually there are 17 variables?
- Is there a too big of a penalty if I set it to 256?
You can refer to the following and the ECMA STANDARD to get a better understanding:
When I run
ildasm.exe
I got this:from the above. I found the max
stakc
value which isn't determined by the push & pop instructions.I didn't know what the real stack number values are. So, I reference the
ildasm
disassembly code to determine the real max stack value..maxstack
is part of the IL verification. Basically.maxstack
tells the JIT the max stack size it needs to reserve for the method. For example,x = y + (a - b)
translates to(Pseudo IL:)
As you can see, there are at most 3 items on the stack at each time. If you'd set
.maxstack
to 2 (or less) for this method, the code wouldn't run.Also, you cannot have something like this as it would require an infinite stack size:
To answer your questions:
Just for the function
You go and see all the paths and return the maximum value possible
It's unrelated to the number of variables, see Lasse V. Karlsen's answer
Doesn't seem like a good idea, but I don't know.
Do you really have to calculate the
.maxstack
yourself?System.Reflection.Emit
calculates it for you IIRC.It has nothing to do with the number of variables declared, but instead everything to do with how many values you need to push on a stack at any given time in order to compute some expression.
For instance, in the following expression, I would assume 2 values needs to be pushed onto the stack:
This is unrelated to the fact that there are at least 3 variables present, x, y, and z, and possibly others as well.
Unfortunately I don't know the answer to your other questions, and I would guess experimentation would be one way to find some answers.