when to use or not Lambda Expressions - c#

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.

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!

Inline helper methods in c#

From this answer I've learned that it is possible to strongly suggest inlining in C# as follows:
using System.Runtime.CompilerServices;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
bool MyCondition() { return someObject != null && someObject.Count > 2; }
In a current project we use statemachines as defined by the Appccelerate StateMachine framework, which results in sequences like the following (which in our project are much longer):
fsm.In(States.A)
.On(Events.B)
.If(arguments => false).Goto(States.B1)
.If(() => someVariable && somethingElse == false).Goto(States.B3);
.If(MyCondition).Goto(States.B2)
In order to simplify these structures I would like to separate the lambda expressions (or Action delegates) into helper methods (i.e. the last statement). Reasons for doing so is that with proper method names it would increase readability of the code, and secondly when autogenerating documentation it will use the method name instead of the non-intuitive [anonymous] text.
The question however, is whether it is any point in using AggressiveInlining or will simple lambda expressions involving upto 4 variables with simple comparison operators be automatically inlined by JIT/compiler?
My gut feeling is to inline these methods, as I believe the different parts of the statemachine will get a lot of hits, and thusly to reduce method calling would be a benefit. But then again how smart is JIT/compiler to automagically do this?
The problem is that you understand lambdas in c# incorrectly. When compiler translate c# to MSIL lambdas become classes and so you have nothing to inline. You can take a look at great Marc Gravell post on SO. So, whether or not you define lambdas in external class, you'll need to get an object from heap (i simplify compiled code behaviour). And so, as i think, there'll be no difference in performance for your application.
Also keep in mind that the state machine keeps the delegate in its internal data structure. The guard action cannot be inlined there.
The only possible thing is to inline the methods that the helper method calls.

c# inline function arguments and temporary variables

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.

C#: Extension methods and the Not operator Best Practice

I have an array of strings and I wish to find out if that array does not contain a certain string. I can use the not operator (!) in conjunction with the Contains method like so:
if (!stringArray.Contains(searchString))
{
//do something
}
The not operator (!) might be overlooked when scanning the code so I was wondering if it was considered bad practice to create an Extension method in an attempt to enhance readability:
public static bool DoesNotContain<T>(this IEnumerable<T> source, T value)
{
return !source.Contains<T>(value);
}
So now the code could read:
if (stringArray.DoesNotContain(searchString))
{
//do something
}
Is this sort of thing frowned upon?
Keep the !. This is where a comment above the line would help readability.
(I suspect ! is more efficient)
//If the word is NOT in the array then...
Another point is to whether you are dead-set on using an Array?
There is something (that you may or may not know about) called a HashSet.
If your sole purpose is to examine whether or not a string is in a list, you are essentially looking at set arithmetic.
Unless you are using the array for something other than finding out whether a certain term is in it or not, try using a HashSet...much faster.
Personally, I wouldn't make an extension method for something so simple. I understand that you're trying to keep it readable but most C# developers should catch the ! operator. It's heavily used and even beginners usually recognize it.
Seems unnecessary, !source.Contains<T>(value); is pretty readable. Also, using the existing Contains function means that your code will be more portable (i.e., it won't be dependent on your extension method being present).
I would definitely use the !stringArray.Contains(string). This what 99.9% of all developers use. DoesNotContain would confuse me at least.
I think your question is based on a bit of a faulty premise. Namely that developers will read past the ! in your code. The ! boolean operator is a very well known operator in a large number of popular programming languages (C, C++, C#, Java, etc ...). Anyone who is likely to read past the ! on a regular basis probably shoudln't be checking in code without a heavy review before hand.
It feels like you`re saying the following
I want people to code in C# but I don't trust them to read it hence I'm going to create a new dialect in my code base with extension methods.
Why stop with the ! operator? It seems just as likely that they would miss the + in += expression or read a | as a ||.
Never seen DoesNot* methods in .NET framework, so I think your problem with ! is overestimated.
I guess this is a personnal choice more than a good/bad practice. IMO I like the extension methods since its more declarative thus more readable, at first glance you know exactly what it does. Just my 2 cents
This sounds like a bad idea, now the consumers of your code have to know about two methods (DoesNotContain and Contains) instead of just one. In general I would avoid XXNotXX methods.
I would personally make an extension method for that if I was going to be using that quite frequently within the project. If it is a one off then i wouldnt bother, but its not really bad practise.
The reason I would do it is because the if() has more context at a glance as to what is going on. Ok granted anyone with a brain cell would know what the current statement is doing, but it just reads nicer. Everyone will have their own preference then...
I made an extension method for formatting strings just to make the code flow better...
I prefer option 1 over option 2. Extension methods are very cool and are great to use for such things as conversions or comparisons that are used frequently. However, Microsoft does recommend to use extension methods sparingly.
I really would consider extension methods which does nothing else than negating an expression as bad practice.
What about:
if (stringArray.Contains(searchString) == false)
{
//do something
}
When !something doesn't work, then fall back to something == false.

When not to use lambda expressions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
A lot of questions are being answered on Stack Overflow, with members specifying how to solve these real world/time problems using lambda expressions.
Are we overusing it, and are we considering the performance impact of using lambda expressions?
I found a few articles that explores the performance impact of lambda vs anonymous delegates vs for/foreach loops with different results
Anonymous Delegates vs Lambda Expressions vs Function Calls Performance
Performance of foreach vs. List.ForEach
.NET/C# Loop Performance Test (FOR, FOREACH, LINQ, & Lambda).
DataTable.Select is faster than LINQ
What should be the evaluation criteria when choosing the appropriate solution? Except for the obvious reason that it's more concise code and readable when using lambda.
Even though I will focus on point one, I begin by giving my 2 cents on the whole issue of performance. Unless differences are big or usage is intensive, usually I don't bother about microseconds that when added don't amount to any visible difference to the user. I emphasize that I only don't care when considering non-intensive called methods. Where I do have special performance considerations is on the way I design the application itself. I care about caching, about the use of threads, about clever ways to call methods (whether to make several calls or to try to make only one call), whether to pool connections or not, etc., etc. In fact I usually don't focus on raw performance, but on scalibility. I don't care if it runs better by a tiny slice of a nanosecond for a single user, but I care a lot to have the ability to load the system with big amounts of simultaneous users without noticing the impact.
Having said that, here goes my opinion about point 1. I love anonymous methods. They give me great flexibility and code elegance. The other great feature about anonymous methods is that they allow me to directly use local variables from the container method (from a C# perspective, not from an IL perspective, of course). They spare me loads of code oftentimes. When do I use anonymous methods? Evey single time the piece of code I need isn't needed elsewhere. If it is used in two different places, I don't like copy-paste as a reuse technique, so I'll use a plain ol' delegate. So, just like shoosh answered, it isn't good to have code duplication. In theory there are no performance differences as anonyms are C# tricks, not IL stuff.
Most of what I think about anonymous methods applies to lambda expressions, as the latter can be used as a compact syntax to represent anonymous methods. Let's assume the following method:
public static void DoSomethingMethod(string[] names, Func<string, bool> myExpression)
{
Console.WriteLine("Lambda used to represent an anonymous method");
foreach (var item in names)
{
if (myExpression(item))
Console.WriteLine("Found {0}", item);
}
}
It receives an array of strings and for each one of them, it will call the method passed to it. If that method returns true, it will say "Found...". You can call this method the following way:
string[] names = {"Alice", "Bob", "Charles"};
DoSomethingMethod(names, delegate(string p) { return p == "Alice"; });
But, you can also call it the following way:
DoSomethingMethod(names, p => p == "Alice");
There is no difference in IL between the both, being that the one using the Lambda expression is much more readable. Once again, there is no performance impact as these are all C# compiler tricks (not JIT compiler tricks). Just as I didn't feel we are overusing anonymous methods, I don't feel we are overusing Lambda expressions to represent anonymous methods. Of course, the same logic applies to repeated code: Don't do lambdas, use regular delegates. There are other restrictions leading you back to anonymous methods or plain delegates, like out or ref argument passing.
The other nice things about Lambda expressions is that the exact same syntax doesn't need to represent an anonymous method. Lambda expressions can also represent... you guessed, expressions. Take the following example:
public static void DoSomethingExpression(string[] names, System.Linq.Expressions.Expression<Func<string, bool>> myExpression)
{
Console.WriteLine("Lambda used to represent an expression");
BinaryExpression bExpr = myExpression.Body as BinaryExpression;
if (bExpr == null)
return;
Console.WriteLine("It is a binary expression");
Console.WriteLine("The node type is {0}", bExpr.NodeType.ToString());
Console.WriteLine("The left side is {0}", bExpr.Left.NodeType.ToString());
Console.WriteLine("The right side is {0}", bExpr.Right.NodeType.ToString());
if (bExpr.Right.NodeType == ExpressionType.Constant)
{
ConstantExpression right = (ConstantExpression)bExpr.Right;
Console.WriteLine("The value of the right side is {0}", right.Value.ToString());
}
}
Notice the slightly different signature. The second parameter receives an expression and not a delegate. The way to call this method would be:
DoSomethingExpression(names, p => p == "Alice");
Which is exactly the same as the call we made when creating an anonymous method with a lambda. The difference here is that we are not creating an anonymous method, but creating an expression tree. It is due to these expression trees that we can then translate lambda expressions to SQL, which is what Linq 2 SQL does, for instance, instead of executing stuff in the engine for each clause like the Where, the Select, etc. The nice thing is that the calling syntax is the same whether you're creating an anonymous method or sending an expression.
My answer will not be popular.
I believe Lambda's are 99% always the better choice for three reasons.
First, there is ABSOLUTELY nothing wrong with assuming your developers are smart. Other answers have an underlying premise that every developer but you is stupid. Not so.
Second, Lamdas (et al) are a modern syntax - and tomorrow they will be more commonplace than they already are today. Your project's code should flow from current and emerging conventions.
Third, writing code "the old fashioned way" might seem easier to you, but it's not easier to the compiler. This is important, legacy approaches have little opportunity to be improved as the compiler is rev'ed. Lambdas (et al) which rely on the compiler to expand them can benefit as the compiler deals with them better over time.
To sum up:
Developers can handle it
Everyone is doing it
There's future potential
Again, I know this will not be a popular answer. And believe me "Simple is Best" is my mantra, too. Maintenance is an important aspect to any source. I get it. But I think we are overshadowing reality with some cliché rules of thumb.
// Jerry
Code duplication.
If you find yourself writing the same anonymous function more than once, it shouldn't be one.
Well, when we are talking bout delegate usage, there shouldn't be any difference between lambda and anonymous methods -- they are the same, just with different syntax. And named methods (used as delegates) are also identical from the runtime's viewpoint. The difference, then, is between using delegates, vs. inline code - i.e.
list.ForEach(s=>s.Foo());
// vs.
foreach(var s in list) { s.Foo(); }
(where I would expect the latter to be quicker)
And equally, if you are talking about anything other than in-memory objects, lambdas are one of your most powerful tools in terms of maintaining type checking (rather than parsing strings all the time).
Certainly, there are cases when a simple foreach with code will be faster than the LINQ version, as there will be fewer invokes to do, and invokes cost a small but measurable time. However, in many cases, the code is simply not the bottleneck, and the simpler code (especially for grouping, etc) is worth a lot more than a few nanoseconds.
Note also that in .NET 4.0 there are additional Expression nodes for things like loops, commas, etc. The language doesn't support them, but the runtime does. I mention this only for completeness: I'm certainly not saying you should use manual Expression construction where foreach would do!
I'd say that the performance differences are usually so small (and in the case of loops, obviously, if you look at the results of the 2nd article (btw, Jon Skeet has a similar article here)) that you should almost never choose a solution for performance reasons alone, unless you are writing a piece of software where performance is absolutely the number one non-functional requirement and you really have to do micro-optimalizations.
When to choose what? I guess it depends on the situation but also the person. Just as an example, some people perfer List.Foreach over a normal foreach loop. I personally prefer the latter, as it is usually more readable, but who am I to argue against this?
Rules of thumb:
Write your code to be natural and readable.
Avoid code duplications (lambda expressions might require a little extra diligence).
Optimize only when there's a problem, and only with data to back up what that problem actually is.
Any time the lambda simply passes its arguments directly to another function. Don't create a lambda for function application.
Example:
var coll = new ObservableCollection<int>();
myInts.ForEach(x => coll.Add(x))
Is nicer as:
var coll = new ObservableCollection<int>();
myInts.ForEach(coll.Add)
The main exception is where C#'s type inference fails for whatever reason (and there are plenty of times that's true).
If you need recursion, don't use lambdas, or you'll end up getting very distracted!
Lambda expressions are cool. Over older delegate syntax they have a few advantages like, they can be converted to either anonymous function or expression trees, parameter types are inferred from the declaration, they are cleaner and more concise, etc. I see no real value to not use lambda expression when you're in need of an anonymous function. One not so big advantage the earlier style has is that you can omit the parameter declaration totally if they are not used. Like
Action<int> a = delegate { }; //takes one argument, but no argument specified
This is useful when you have to declare an empty delegate that does nothing, but it is not a strong reason enough to not use lambdas.
Lambdas let you write quick anonymous methods. Now that makes lambdas meaningless everywhere where anonymous methods go meaningless, ie where named methods make more sense. Over named methods, anonymous methods can be disadvantageous (not a lambda expression per se thing, but since these days lambdas widely represent anonymous methods it is relevant):
because it tend to lead to logic duplication (often does, reuse is difficult)
when it is unnecessary to write to one, like:
//this is unnecessary
Func<string, int> f = x => int.Parse(x);
//this is enough
Func<string, int> f = int.Parse;
since writing anonymous iterator block is impossible.
Func<IEnumerable<int>> f = () => { yield return 0; }; //impossible
since recursive lambdas require one more line of quirkiness, like
Func<int, int> f = null;
f = x => (x <= 1) ? 1 : x * f(x - 1);
well, since reflection is kinda messier, but that is moot isn't it?
Apart from point 3, the rest are not strong reasons not to use lambdas.
Also see this thread about what is disadvantageous about Func/Action delegates, since often they are used along with lambda expressions.

Categories