c# inline function arguments and temporary variables - c#

I was wondering about the following situation in C#.
Sometimes function names can be quite long, and verbose. I'm using Microsoft's MVC 3 framework for a website at work, Here's an example function:
[ImportModelStateFromTempData]
[BreadCrumb("New Event")]
public ActionResult New()
{
var #event = _dbContext.EventRepository.CreateNewEvent();
return View("New",
EventViewModel.FromEventDomainModel(#event));
}
This code could be rewritten without use of the temporary variables #event, like so:
[ImportModelStateFromTempData]
[BreadCrumb("New Event")]
public ActionResult New()
{
return View("New",
EventViewModel.FromEventDomainModel(_dbContext.EventRepository.CreateNewEvent()));
}
The first example is obviously more clear, but from a pure curiosity perspective/performance perspective, is either faster than the other? Especially considering that the cached value #event is only being used once.
In C++ I remember finding out that the local variable declaration of #event (if this were C++) would be stored in New()'s stack frame, and the assembly generated would be SLIGHTLY slower than directly in-lining the argument (as opposed to storing it in a temporary).
Is the C# compiler smarter about this situation? Am I free to use temporary's without the same performance considerations?
I understand that pre-optimization is evil, and I absolutely should not be worried about this kind of this, but I am curious about this. I'm not even sure about where I would go looking up more information about this, as the title was the best way I could describe my question. So what do you think Stack Overflow?

The IL produced by these will be equivalent. If you want to prove it to yourself, try compiling both and looking at the resulting IL with Ildasm http://msdn.microsoft.com/en-us/library/f7dy01k1(v=vs.80).aspx

Temporary variables are good.
When you are debugging, you can check the results of functions.
The delay, if there is one, is in nano or pico seconds.
Maintenance is king.

Related

Does c# inline method? [duplicate]

How do you do "inline functions" in C#? I don't think I understand the concept. Are they like anonymous methods? Like lambda functions?
Note: The answers almost entirely deal with the ability to inline functions, i.e. "a manual or compiler optimization that replaces a function call site with the body of the callee." If you are interested in anonymous (a.k.a. lambda) functions, see #jalf's answer or What is this 'Lambda' everyone keeps speaking of?.
Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining value. It is also available in the Mono's trunk (committed today).
// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
1. Previously "force" was used here. I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible. Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.
Inline methods are simply a compiler optimization where the code of a function is rolled into the caller.
There's no mechanism by which to do this in C#, and they're to be used sparingly in languages where they are supported -- if you don't know why they should be used somewhere, they shouldn't be.
Edit: To clarify, there are two major reasons they need to be used sparingly:
It's easy to make massive binaries by using inline in cases where it's not necessary
The compiler tends to know better than you do when something should, from a performance standpoint, be inlined
It's best to leave things alone and let the compiler do its work, then profile and figure out if inline is the best solution for you. Of course, some things just make sense to be inlined (mathematical operators particularly), but letting the compiler handle it is typically the best practice.
Update: Per konrad.kruczynski's answer, the following is true for versions of .NET up to and including 4.0.
You can use the MethodImplAttribute class to prevent a method from being inlined...
[MethodImpl(MethodImplOptions.NoInlining)]
void SomeMethod()
{
// ...
}
...but there is no way to do the opposite and force it to be inlined.
You're mixing up two separate concepts. Function inlining is a compiler optimization which has no impact on the semantics. A function behaves the same whether it's inlined or not.
On the other hand, lambda functions are purely a semantic concept. There is no requirement on how they should be implemented or executed, as long as they follow the behavior set out in the language spec. They can be inlined if the JIT compiler feels like it, or not if it doesn't.
There is no inline keyword in C#, because it's an optimization that can usually be left to the compiler, especially in JIT'ed languages. The JIT compiler has access to runtime statistics which enables it to decide what to inline much more efficiently than you can when writing the code. A function will be inlined if the compiler decides to, and there's nothing you can do about it either way. :)
Cody has it right, but I want to provide an example of what an inline function is.
Let's say you have this code:
private void OutputItem(string x)
{
Console.WriteLine(x);
//maybe encapsulate additional logic to decide
// whether to also write the message to Trace or a log file
}
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{ // let's pretend IEnumerable<T>.ToList() doesn't exist for the moment
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
OutputItem(y);
}
return result;
}
The compilerJust-In-Time optimizer could choose to alter the code to avoid repeatedly placing a call to OutputItem() on the stack, so that it would be as if you had written the code like this instead:
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
// full OutputItem() implementation is placed here
Console.WriteLine(y);
}
return result;
}
In this case, we would say the OutputItem() function was inlined. Note that it might do this even if the OutputItem() is called from other places as well.
Edited to show a scenario more-likely to be inlined.
Do you mean inline functions in the C++ sense? In which the contents of a normal function are automatically copied inline into the callsite? The end effect being that no function call actually happens when calling a function.
Example:
inline int Add(int left, int right) { return left + right; }
If so then no, there is no C# equivalent to this.
Or Do you mean functions that are declared within another function? If so then yes, C# supports this via anonymous methods or lambda expressions.
Example:
static void Example() {
Func<int,int,int> add = (x,y) => x + y;
var result = add(4,6); // 10
}
Yes Exactly, the only distinction is the fact it returns a value.
Simplification (not using expressions):
List<T>.ForEach Takes an action, it doesn't expect a return result.
So an Action<T> delegate would suffice.. say:
List<T>.ForEach(param => Console.WriteLine(param));
is the same as saying:
List<T>.ForEach(delegate(T param) { Console.WriteLine(param); });
the difference is that the param type and delegate decleration are inferred by usage and the braces aren't required on a simple inline method.
Where as
List<T>.Where Takes a function, expecting a result.
So an Function<T, bool> would be expected:
List<T>.Where(param => param.Value == SomeExpectedComparison);
which is the same as:
List<T>.Where(delegate(T param) { return param.Value == SomeExpectedComparison; });
You can also declare these methods inline and asign them to variables IE:
Action myAction = () => Console.WriteLine("I'm doing something Nifty!");
myAction();
or
Function<object, string> myFunction = theObject => theObject.ToString();
string myString = myFunction(someObject);
I hope this helps.
The statement "its best to leave these things alone and let the compiler do the work.." (Cody Brocious) is complete rubish. I have been programming high performance game code for 20 years, and I have yet to come across a compiler that is 'smart enough' to know which code should be inlined (functions) or not. It would be useful to have a "inline" statement in c#, truth is that the compiler just doesnt have all the information it needs to determine which function should be always inlined or not without the "inline" hint. Sure if the function is small (accessor) then it might be automatically inlined, but what if it is a few lines of code? Nonesense, the compiler has no way of knowing, you cant just leave that up to the compiler for optimized code (beyond algorithims).
There are occasions where I do wish to force code to be in-lined.
For example if I have a complex routine where there are a large number of decisions made within a highly iterative block and those decisions result in similar but slightly differing actions to be carried out. Consider for example, a complex (non DB driven) sort comparer where the sorting algorythm sorts the elements according to a number of different unrelated criteria such as one might do if they were sorting words according to gramatical as well as semantic criteria for a fast language recognition system. I would tend to write helper functions to handle those actions in order to maintain the readability and modularity of the source code.
I know that those helper functions should be in-lined because that is the way that the code would be written if it never had to be understood by a human. I would certainly want to ensure in this case that there were no function calling overhead.
I know this question is about C#. However, you can write inline functions in .NET with F#. see: Use of `inline` in F#
No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
(I think it should :-))
In case your assemblies will be ngen-ed, you might want to take a look at TargetedPatchingOptOut. This will help ngen decide whether to inline methods. MSDN reference
It is still only a declarative hint to optimize though, not an imperative command.
Lambda expressions are inline functions! I think, that C# doesn`t have a extra attribute like inline or something like that!

Exposing a GUID via a static property - is it more efficient to use old fashioned property syntax

I have a static C# class that exposes some pre known Guids via properties
I used the old fashioned property syntax e.g a private declaration that declares the guid and a public property that exposes it. e.g. something like
private static Guid aGuid = new Guid("l1....");
public static Guid AGuid { get { return aGuidl }}
But would be less code just to have the automatic property e.g.something like
public static Guid AGuid { get{ return new Guid("11...") }}
The question is, is the former more verbose method more efficient or is the C# compiler clever enough not to create a new Guid every time if I use the later approach.
Caching (your 1st sample) would be a little more efficient here.
The compiler won't do this as an optimization.
I just did a quick check with Ildasm.
It's not an unreasonable assumption, we all know the Guid constructor should yield the same value every time. But the compiler cannot assume this, there would have to be a list of special types, probably not worth the trouble.
Necessary preamble:
Like most micro optimizations, the answer is probably, "who cares?" It's unlikely to be the thing that's actually slowing down your program.
This is an easy thing to do a quick empirical test. However, like all empirical tests, you should be skeptical of your results. The answer may be dependent upon a lot of unobserved or unobservable confounds.
Henk Holterman is correct that the IL will appear to be more efficient in the first form. The constructor that takes a string has to do some parsing. Parsing isn't slow, but it's not free either. It might be possible to improve performance easily by using a Guid constructor that takes a series int types instead of a string.
Also, Guid is a value type. This means that no matter what, you'll have to pay the cost of copying the memory when you return the Guid (yeah, I know, it's a really steep cost to copy 16 bytes).
Finally, and I'm getting a bit speculative here, it's entirely possible that the JITer can recognize side-effect free constructors and unroll them at JIT time into "plain old data." If this is the case then the total cost may be just a 16 byte memcpy, which is unavoidable anyway.
So... write it both ways, test it both ways in a variety of conditions. You'll likely find it doesn't matter at all, but you also might find a small performance boost.

Is there a good way to get the current property name?

I know there are ways, but is there actually a good way?
At the moment I have a decent Attribute based framework which is working really well with the exception of the verbosity of:
public Variable<int> Value { get { return Get.Int(MethodBase.CurrentMethod()); } }
Picture that, * a few hundred (with setters often too). Is there anyway to get the same result but more concise?
I've considered:
public Variable<int> Value { get { return Get.Int("Value"); } }
and tried:
public Variable<int> Value { get { return Get.Int(() => Value); } }
But as there's many, many of these variables (there is method in this madness, I promise) I'm concerned about obscure bugs arising from the second Value (or string) not matching the first.
So my question is, can anyone think of a neater way to write the above? All I need is the current property name.
My favourite "solution" so far has been:
protected Func<MethodBase> Self = MethodBase.GetCurrentMethod;
public Variable<int> Value { get { return Get.Int(Self()); } }
Which is short, sweet, and pretty to look at.
But alas the JIT kills rules that out as an option. Is there perhaps a way I can rewrite GetCurrentMethod in C#, under a different name? It's a pity StackCrawlMark (which I believe is required) is internal to System.
Alternatively, are there any tools out there that are compatible with ReSharper but perhaps let me view the code through goggles, reducing the verbose MethodBase.GetCurrentMethod to something shorter and sweeter, whilst still compiling exactly the same? (I'd really rather not have a pre-compile fiddling step, but am open to suggestions - one that reduced it all to the property name would be nice).
In short, no. There are various attempts at this, including stack inspection (GetCurrentMethod) and lambda expressions, but ultimately they are all a bit inefficient.
Unless you need need obfuscation, I would just use a string - Get.Int("Value") - this is very unlikely to be a genuine maintenance problem.
The stack inspection approach suffers from potential brittleness if it inlines; if you need obfuscation, I would probably go with Expression. Or just mark the method as "don't obfuscate this name".
Another approach would be to have an abstract base type, and use meta-programming to create the concrete type with the right data/code at runtime, based on inspecting your attributes.

when to use or not Lambda Expressions

I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.
Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language.
Other factors against are the cost using reflection by lambda and that not friendly to debugging.
I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions.
(this is not the better example, but let's say it was the trigger)
I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = delegate { return null;}
Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = () => null;
At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.
There are somewhat two questions here.
First, as for your example, using a lambda vs. using the anonymous delegate syntax. The generated code by the compiler will be identical, so it does not come down to a performance difference, but rather a readability difference.
Personally, I find the lambda syntax easy to follow. I find that the lambda syntax is almost always cleaner, more concise, and more understandable than the anonymous delegate syntax, so I prefer it nearly always.
As for using lambda expressions throughout the code - Personally, I am a fairly heavy user of them. I find that they often make life much easier than having lots of methods defined. If a piece of code is not going to be reused by any other methods (it will only be called and exist in one place), I will use a lambda to express it.
If a piece of code is going to be used more than once, it should be pulled out into a (non-anonymous) method. Also, if a piece of code is something that could and should be tested, I tend to make a method for it, since that eases testability.

C# Compiler Enhancement Suggestion

Imagine someone coding the following:
string s = "SomeString";
s.ToUpper();
We all know that in the example above, the call to the “ToUpper()” method is meaningless because the returned string is not handled at all. But yet, many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “Why aren’t the characters on my ‘s’ variable capitalized”????
So wouldn’t it be great if there was an attribute that could be applied to the “ToUpper()” method that would yield a compiler error if the return object is not handled? Something like the following:
[MustHandleReturnValueAttribute]
public string ToUpper()
{
…
}
If order for this code to compile correctly the user would have to handle the return value like this:
string s = "SomeString";
string uppers = s.ToUpper();
I think this would make it crystal clear that you must handle the return value otherwise there is no point on calling that function.
In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy.
What do you guys think?
Thanks.
Does one call a method for its side-effects, for its return value, or for both? "Pure" functions (which have no effects and only serve to compute a return value) would be good to annotate as such, both to eliminate the type of error you describe, as well as to enable some potential optimizations/analyses. Maybe in another 5 years we'll see this happen.
(Note that the F# compiler will warn any time you implicitly ignore a return value. The 'ignore' function can be used when you want to explicitly ignore it.)
If you have Resharper it will highlight things like this for you. Cant recommend resharper highly enough, it has lots of useful IDE additions especially around refactoring.
http://www.jetbrains.com/resharper/
I am not sure that I like this. I have called many a method that returns a value that I choose not to capture. Adding some type of default (the compiler generates a warning when a return value is not handled) just seems wrong to me.
I do agree that something along the suggested lines might help out new programmers but adding an attribute at this point in the game will only affect a very small number of methods relative the the large existing body. That same junior programmer will never get their head around the issue when most of their unhandled return values are not flagged by the compiler.
Might have been nice way back when but the horses are out of the barn.
I'd actually prefer a way to flag a struct or class as [Immutable], and have this handled automatically (with a warning) for methods called without using their return values on immutable objects. This could also protect the object by the compiler from changes after creation.
If the object is truly an immutable object, there really would be no way to handle it. It also could potentially be used by compilers to catch other common mistakes.
Tagging the method itself seems less useful to me, though. I agree with most of the other comments regarding that. If the object is mutable, calling a method could have other side-effects, so the above code could be perfectly valid.
I'm having flashbacks to putting (void) casts on all printf() calls because I couldn't get Lint to shut up about the return value being ignored.
That said, it seems like this functionality should be in some code checker tool rather than the compiler itself.
At least a compiler-warning would be helpful. Perhaps they add something similar for C# 4.0 (Design-By-Contract).
This doesn't warrant for a warning or pragma. There are too many places where it is intended to discard the result, and I'd be quite annoyed getting a warning/error from the compiler just because the method was decorated with some dodge attribute.
This kind of 'warning' should be annotated in the IDE's Editor, like a small icon on the gutter "Warning: Discarding return value" or similar.

Categories