views:

30

answers:

1

I'm working on writing a compiler and one feature of this compiler is that it automatically generates GetHashCode(), Equals(object), and Equals({this value type}) methods for value types. Right now the Equals({this value type}) implementation basically generates il equivalent to the il generated by this c#:

public bool Equals(ThisType o)
{
    return Field1 == o.Field1 && Field2 == o.Field2 && Field3 == o.Field3;//etc
}

My compiler pushes all of these objects on to the stack and then begins comparing and "and"ing them together. This causes the method's .maxstack to become large very quickly. Is there a penalty for this? If so, at what point should I start pushing values into locals?

Thanks.

+1  A: 

Why don't you measure the scenarios which are important to you and find out? Your performance could potentially vary across .NET versions or processor architectures, so you really out to measure the variants that you care about. As I understand it, maxstack is mainly used for verification, so I would guess that there won't be much of a performance penalty, but the only way to know for sure is to actually measure.

Additionally, in your case you don't need any locals to avoid growing the stack, anyway. You could just do something like this instead:

  load Field1
  load o.Field1
  branch to end if not equal
  load Field2
  load o.Field2
  branch to end if not equal
  ...
  return true
end:
  return false

This uses constant stack space regardless of the number of fields.

kvb