I have implemented a compiler and virtual machine for a language. The implementation is in C# and the stack-based VM uses reflection to make function calls on a set of built-ins.
Much of the code involves simply pushing and popping stack values, but the workhorse is the function call. Currently the implementation of a function call looks like this:
var calli = gencode[pc++] as CallInfo;
var calla = PopStackList(calli.NumArgs).ToArray();
var ret = calli.MethodInfo.Invoke(instance, calla);
if (ret != null) PushStack(ret);
All data items passed and returned are objects using a custom type system (no native types used). Clarification: this is an instance method, not static.
Performance testing suggests that this MethodInfo.Invoke is quite slow. The question is how to make function calls at the highest possible speed, presumably by doing more preparatory work in the compiler and generating better code.
In response to suggestions, one possibility is to create a delegate. Unfortunately as far as I can tell a delegate has to be bound to a specific instance of a class, or to a static method, and creating a delegate after creating the instance rather defeats the purpose.
I see a vote to close, but to my eye the question is not broad at all. How should a compiler implement functions calls on instance methods in a virtual machine for best performance, at the very least faster than MethodInfo.Invoke()?
Well, if you’re sure your main problem is MethodInfo.Invoke…
Use stuff from System.Linq.Expressions (Expression.Call, Expression.Parameter) to create an expression that calls that MethodInfo method, passing your parameters for instance + arguments.
Compile that expression into Action<tInstance, tArgs[]> (don't know your types of these).
Cache that Action in your CallInfo class instance.
Invoke that action as needed.
How to convert MethodInfo.Invoke to delegate:
Normally when you’re calling methods with reflection, you call MethodInfo.Invoke. Unfortunately, this proves to be quite slow. If you know the signature of the method at compile-time, you can convert the method into a delegate with that signature using Delegate.CreateDelegate(Type, object, MethodInfo). You simply pass in the delegate type you want to create an instance of, the target of the call (i.e. what the method will be called on), and the method you want to call. It would be nice if there were a generic version of this call to avoid casting the result, but never mind. Here’s a complete example demonstrating how it works:
using System;
using System.Reflection;
public class Test
{
static void Main()
{
MethodInfo method = (string).GetMethod(“IndexOf”, new Type[]{typeof(char)});
Func<char, int> converted = (Func<char, int>)
Delegate.CreateDelegate(typeof(Func<char, int>), “Hello”, method);
Console.WriteLine(converted(‘l’));
Console.WriteLine(converted(‘o’));
Console.WriteLine(converted(‘x’));
}
}
This prints out 2, 4, and -1; exactly what we’d get if we’d called "Hello".IndexOf(...) directly. Now let’s see what the speed differences are…
We’re mostly interested in the time taken to go from the main calling code to the method being called, whether that’s with a direct method call, MethodInfo.Invoke or the delegate. To make IndexOf itself take as little time as possible, I tested it by passing in ‘H’ so it would return 0 immediately. As normal, the test was rough and ready, but here are the results:
Invocation type Stopwatch ticks per invocation
Direct 0.18
Reflection 120
Delegate 0.20
Copied from: https://blogs.msmvps.com/jonskeet/2008/08/09/making-reflection-fly-and-exploring-delegates/
Related
I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps
I am trying to desconstruct a method written by another coder to see how it works but it's getting a bit confusing
We have a Delegate that takes an Action as parameter.
private delegate void FunctionDelegate(Action next);
A function is then called in the constructor that takes an array of these delegates as parameter and executes each value in the array
LoadInSeries(LoadRoleAreaHours, LoadTableData);
The Function looks like this
private void LoadInSeries(params FunctionDelegate[] _delegates)
{
var Delegates = new List<FunctionDelegate>(_delegates);
Func<Action, Action> creator = null;
creator = delegate(Action inner)
{
if (Delegates.Count > 0)
{
FunctionDelegate L = Delegates.First();
Delegates.RemoveAt(0);
Action next = delegate { L(inner); };
return creator(next);
}
else return inner;
};
Action outer = creator(null);
if (outer != null)
outer();
}
The intent was too chain a series of functions with each function calling the next but wouldnt it just be easy to use a multicast delegate and add each function to the invocation list.
Does this code do something different?
Without a good Minimal, Complete, and Verifiable code example, it's impossible to understand the code fully. Of most significant concern is that your code example includes a mysterious L() method, the behavior of which we have no idea. There is also the problem with the FunctionDelegate = Delegates.First(); statement. At best, the FunctionDelegate identifier refers to a class field or property; at worst, that statement won't even compile. Either way, there's no evidence that the delegate object being removed from the input list is ever actually invoked.
So to even answer the question, some basic assumptions have to be made, which may or may not be correct.
That said, in the best-case scenario — which is that the code has hidden some awful, convoluted mechanism in the L() method that ultimately winds up able to invoke the delegate for the current call to the creator delegate — the code you're looking at is not simply invoking delegates in sequence, as would be the case with a MulticastDelegate. Rather, the code is constructing a chain of calls to the L() method, passing each delegate instance to the method in sequence.
Since you didn't show us the L() method, there's no way to say what the code actually does. I would agree that if all that L() does is invoke the delegate you pass to it, then this code looks like a very complicated way to just invoke an array of delegates. But, giving the benefit of the doubt to the person who wrote the code, this simply means that L() probably does something other than simply invoke the delegate.
Of course, it's possible the author of the code doesn't deserve the benefit of the doubt. In that case, not only would it be simpler to just use a multicast delegate, the simplest implementation would just iterate over the array, invoking each delegate in the desired sequence. But I say that without really knowing what the code does. I'm just assuming it's intended to do something useful with the delegates that are passed to it. There's no evidence in the code you posted to support even that generous assumption.
Give us the full picture, and a more definitive answer can be provided. Without knowing what L() is, or what side effects might exist in the passed-in delegates' target methods, it's impossible to say for sure whether the code you're looking at really needs to be written that way or not.
I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps
I am using Reflection.Emit to build a mathematical expression parser (e.g. 2+2). A class takes in an infix expression (e.g. 2+2), turns it into a postfix expression (e.g. 2 2 +), and then another class compiles that postfix expression into IL and creates a DynamicMethod. From there, the expression can be evaluated as if it had been created at compile time, with similar speed.
This compiler also supports implicit multiplication, so something like x(2 + 2) evaluates as x * (2 + 2)
Right now, I am attempting to implement user-defined functions (e.g. f(x)). A problem arises when I try to differentiate between implicit multiplication, as shown above, and user defined functions. An example of this is if a user inputs x(5), how do I know whether they want to multiply x by 5, or invoke the x function with an argument of 5?
To solve this, in the previous case, the compiler inserts an if statement into the IL stream. It calls a function to determine if the function is defined with the identifier of x. If there is, then it inserts a MethodInfo instance onto the stack through an out variable and a local.
My actual question is, is it possible to execute a method using the MethodInfo instance on the stack that is equivalent in speed to calling IlGenerator.Emit(OpCodes.Call, MethodInfo) during compilation?
Thanks.
The only way I am aware of that allows you to invoke a MethodInfo instance on the stack is by invoking the Invoke method on it. I’m sure you are already aware of this possibility, but you fear that it may be too slow. I recommend that you try it and time the performance under stress. You might find that it is fast enough for your purposes.
If it isn’t, then you will have to think about how to restructure your design so that you don’t pass around MethodInfo instances. You could, for example, pass managed function pointers instead. Those are the things that the ldftn and ldvirtftn instructions return. You can then use the calli instruction to invoke one of those. You will need to construct the “call-site description”, which calli expects as an operand, using the SignatureHelper class.
I'm just looking at some of my code and it occurred to me that given,
Action<int> fireMessage = FireMessages;
fireMessage.BeginInvoke(1, r => fireMessage.EndInvoke(r), null);
As I can directly assign a method to a delegate, why can't I just call BeginInvoke on the method directly. The way this code reads suggests that the delegate assignment is redundant.
But calling BeginInvoke directly on the method throws up a compiler exception.
A method isn't a delegate - a delegate is distinct type which references a method - there is actually more information in a delegate than just the method.
Techically, it might be possible for the compiler to wire this up for you and shorten the typing, but I'm actually somewhat thankful that this wasn't done. By forcing you to assign a delegate to a method reference on an object, then invoke the delegate using BeginInvoke, the compiler is forcing you to be more explicit in your desire here.
Calling a delegate via BeginInvoke potentially has some serious side effects - this should be an explicit, purposeful action. Many methods will not behave as expected if they're called in separate threads, and at least this way, you need to know what you're doing in order to work in this manner.
That being said, in .NET 4, I'd recommend changing how you "fire methods" in "background threads". Instead of using Delegate.BeginInvoke, I'd recommend considering changing to using the new Task class:
Task.Factory.StartNew( () => FireMessages(1) );
There are many advantages to the new task library, especially when it comes to error handling, cancellation, prevention of oversubscription on the thread pool, etc.
There is a bit of syntactic sugar here. A delegate is really under the hood an object that wraps your method, and it happens to have the BeginInvoke method defined. The syntactic sugar is that you can assign a "method" to a delegate (without explicitly creating a delegate), but it only works in this context.
I think it is by design. In C# methods are not objects like they are in functional languages, but delegates are.
Delegate constructor is "point of touching" that is supported by C# compiler, and this is single place where method is used as 'method reference' instead of 'method invokation'.
Accessing 'instance's method instance' object using someInstance.Method.SomeMethodOfMethod have confusing syntax, and requires method instance. Some person may expect method instances obtained from the same method of the same object must be also same, and this will requires additional memory usage to store method instance inside object.
The compiler can automatically produce a delegate from a method group if it knows the type of delegate to produce. It cannot, however, infer the type of a delegate based upon a method group because different delegate types are in general not compatible, even if the signatures match. Although there are many situations where the compiler could in fact use any delegate with a particular signature, the compiler has no way of knowing what those situations are. Consequently, method groups are only converted implicitly to delegates in cases where the compiler can identify the delegate type via other means.