I have written a parser-generator that has expressions like this:
a = f:"foo" "bar" { /* your code here */ }
Which, after a fashion, generates code that looks about like this:
r0 = this.ReturnHelper<string>(cursor, cursor, () => /* your code here */);
This is perfect, because the users can specify an expression, like f to just return a value, or they can add an extra set of curly braces and write a method. So far so good.
Now, I also allow assertions like this:
a = w:word !{ w == "disallowed" }
Which compiles into something like this, currently:
var w = this.ParseWord(...).Value;
...
if (!( w == "disallowed" ))
{
r2 = new ParseResult<string>(cursor, cursor, string.Empty);
}
I would LIKE to have the assertions support the same method-body option that the ReturnHelper provides, but it seems inefficient to have a method bool AssertionHelper(Func<bool> assertion) that just calls the predicate.
I was imagining that new Func<bool>(() => /* your code here */)() would work, but I’m not sure that it is the most efficient.
Any ideas?
EDIT
How about Nope, that generates identical IL to the above version.((Func<bool>)(() => /* code */))()? Does that avoid an allocation?
It’s not clear why you need to mention
Func<bool>explicitly at all. Why not just:? Assuming it’s going to be a single expression with no parameters and it’s of type
bool, that should be fine.If it needs a parameter
w, just change it to:I believe the MS implementation of the C# compiler will avoid creating a new delegate instance on each invocation of this – but really, does it matter? Have you profiled your application to check whether this is actually a significant performance hit at all? If you have, that’s fine – and I’ve certainly seen some interesting data around some cases where micro-optimization for delegates can make a difference – but I wouldn’t worry about it until I’d found it’s an actual problem.