• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ATC

Will using LINQ hurt engine performance (C#)?

14 posts in this topic

Hey guys,

I am considering what performance implications the use of LINQ/C# could have on my engine's overall performance. I don't think it's any secret that queries are a bit slower (sometimes significantly slower) that plain old C# code. But I'm wondering how big of an impact that could have in a very specific set of contexts. For instance, I use a dash of LINQ in my "GameComponent" classes for sorting out child components, like so:

[source lang="csharp"]
public virtual void Update(GameTime gameTime) {

if (!Enabled)
return;

var components = (
from component in ChildComponents
orderby component.UpdateOrder ascending
where component.Enabled
select component).ToArray();

for (int i = 0; i < components.Length; ++i)
components[i].Update(gameTime);

if (Updated != null)
Updated(this, EventArgs.Empty);
}
[/source]

The code is definitely very concise and pretty, but how about performance? I'm thinking it's [i]not [/i]going to be a bottleneck because the number of "GameComponents" will rarely number more than a few tens at the maximum. And it's my understanding that LINQ queries have grown faster in C# 5.0. When the performance hit is very marginal, I tend to favor very "elegant" code like this; it's easy to read, modify and maintain. Another one of my programmers can take one look at this and instantly know what the code is doing. In that way I think a "dash" of LINQ here and there can be helpful in the overall structure of software.

So the question isn't will there be a performance hit... there definitely will be [i]some[/i] penalty to pay for using a bit of LINQ here and there. But is it enough to worry about or lose any sleep over? Should I get rid of all LINQ-stuff and rewrite it in "pure" C#? My question isn't about this one, particular method, GameComponent.Update(GameTime), but about situations like these and the use of LINQ in general...

Regards,

--ATC--
0

Share this post


Link to post
Share on other sites
My immediate answer is "no". I can't see using LINQ especially in .NET 4.0 and above as a performance killer. Even in .NET 3.5, it's pretty good.
2

Share this post


Link to post
Share on other sites
I'm only a beginner with LINQ, but from what I can tell, the order in which you use LINQ statements can have a big impact on what computation is done.
e.g. [font=courier new,courier,monospace]where[/font] filters the number of objects, so it should be done before projection ([i]i.e. [font=courier new,courier,monospace]select[/font][/i]) or sorting.
2

Share this post


Link to post
Share on other sites
To both of you: what LINQ resources are you using to learn LINQ. I've dabbled at it, but admittedly, I'm certainly not an expert.

Also, do you use query syntax or lambda syntax? Out of curiosity. Edited by Alpha_ProgDes
1

Share this post


Link to post
Share on other sites
There are some caveats when using LINQ, such as understanding how lazy evaluation works (and especially when querying against databases).

For example, if you only iterate thru the query once, you're better of not making an array, but just do a foreach on it, such as:

[CODE]
var components = (
from component in ChildComponents
orderby component.UpdateOrder ascending
where component.Enabled
select component);
foreach (var component in components)
component.Update(gameTime);
[/CODE]

If you on the other hand are going to iterate thru it many times, then you better cache it into an array, otherwise it will query and sort it each time you iterate.

That said, I don't think you can write a non-LINQ version of that particular code (i.e. tens of items once every game loop) that will provide you with significantly better performance. It should perform about the same as any non-LINQ version. Edited by Felix Ungman
1

Share this post


Link to post
Share on other sites
Thanks everyone...

I changed the queries so that the "where" filter comes before sorting. It seems logical that it will sift out components that aren't enabled and speed up the sorting that follows. If it doesn't, oh well...only had to copy and paste one line of code so no loss. Of course jbadams is right though, and only actually profiling it will tell the true tale of performance...
0

Share this post


Link to post
Share on other sites
[quote name='Alpha_ProgDes' timestamp='1351229266' post='4994040']
To both of you: what LINQ resources are you using to learn LINQ. I've dabbled at it, but admittedly, I'm certainly not an expert.

Also, do you use query syntax or lambda syntax? Out of curiosity.
[/quote]I've just been learning from examples on MSDN and using google for specific questions -- most of these searches bring up a StackExchange page where someone's already asked my question.

I'm using the Lambda syntax at the moment, because I love C# lambdas ;)
1

Share this post


Link to post
Share on other sites
[quote name='Felix Ungman' timestamp='1351230835' post='4994042']
That said, I don't think you can write a non-LINQ version of that particular code (i.e. tens of items once every game loop) that will provide you with significantly better performance. It should perform about the same as any non-LINQ version.
[/quote]

Other than the really obvious improvement of just keeping your component list in sorted order, all the time. What order are they stored in normally? If it's arbitrary, then save yourself the trouble of sorting them every frame... (And you could go further and maintain two collections in the entitiy - one for enabled components, one for disabled). Move components between them on state change. Now you need zero LINQ code because you need to do zero work.
1

Share this post


Link to post
Share on other sites
[quote name='osmanb' timestamp='1351345988' post='4994413']
Other than the really obvious improvement of just keeping your component list in sorted order, all the time. What order are they stored in normally? If it's arbitrary, then save yourself the trouble of sorting them every frame... (And you could go further and maintain two collections in the entitiy - one for enabled components, one for disabled). Move components between them on state change. Now you need zero LINQ code because you need to do zero work.
[/quote]

It was just example code, but you're right... and I don't actually sort on every frame. Only if the component list has been changed. But you also have to check (or mark "dirty") for changes to the UpdateOrder property which will require a resort. Still, using LINQ is a quite elegant solution to the problem imho
0

Share this post


Link to post
Share on other sites
I asked myself this very same question not long ago, whilst building a game with SDL.NET in C#. I had a bunch of LINQ expressions (lambda syntax) sprinkled throughout my code for the same reasons you mention - it is very readable and easy to get a grip on what is going on.

It then got to the point where I needed to find places I could speed up a few hot sections of code, and it turned out that by abandoning LINQ in favour of hand-written alternatives I was able to get quite a big performance boost in several places which made a noticeable FPS difference. This was because I was using these LINQ expressions in places that were being called [b]every frame[/b], which is not ideal. If it's something you're only calling every now and then, I guess it's fine. But for code getting hit every frame, you really want things to be as fast as possible, as you'll inevitably rewrite it later to get the best performance possible.
1

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1351228837' post='4994039']
I'm only a beginner with LINQ, but from what I can tell, the order in which you use LINQ statements can have a big impact on what computation is done.
e.g. [font=courier new,courier,monospace]where[/font] filters the number of objects, so it should be done before projection ([i]i.e. [font=courier new,courier,monospace]select[/font][/i]) or sorting.
[/quote]

When using the SQL-like syntax (ie. "from n in <collection> where <condition>..." etc.), wouldn't the compiler take care of that kind of thing? Is the C# compiler smart enough to notice that you're doing a filter and a projection together, and do the projection after the filter?
0

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1351575900' post='4995300']
When using the SQL-like syntax (ie. "from n in <collection> where <condition>..." etc.), wouldn't the compiler take care of that kind of thing? Is the C# compiler smart enough to notice that you're doing a filter and a projection together, and do the projection after the filter?
[/quote]

One really elegant aspect of C#/Linq is that the sql query syntax is really just syntactic sugar. You can roll your own classes with methods having the corresponding signatures. They need not have any relationship with the standard ones and you can still use the query syntax. So the choice of syntax doesn't matter performance wise.

On the other hand, if queries agains a database linq-provider get translated into expression trees. It is up to the linq-provider to do any optimization of this query tree. Different providers do it differently. However, the Linq-to-objects provider doesn't optimize (by design).
0

Share this post


Link to post
Share on other sites
[quote name='Felix Ungman' timestamp='1351584431' post='4995327']
[quote name='Oberon_Command' timestamp='1351575900' post='4995300']
When using the SQL-like syntax (ie. "from n in <collection> where <condition>..." etc.), wouldn't the compiler take care of that kind of thing? Is the C# compiler smart enough to notice that you're doing a filter and a projection together, and do the projection after the filter?
[/quote]

One really elegant aspect of C#/Linq is that the sql query syntax is really just syntactic sugar. You can roll your own classes with methods having the corresponding signatures. They need not have any relationship with the standard ones and you can still use the query syntax. So the choice of syntax doesn't matter performance wise.
[/quote]

So in other words, the compiler doesn't optimize the translation from the query syntax to the lambda syntax?
0

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1351632078' post='4995584']
So in other words, the compiler doesn't optimize the translation from the query syntax to the lambda syntax?
[/quote]

The compiler would need to prove that the lambda functions used in the query do not have side effects, and it would also need to understand whether the select/where functions are associative or not (even for user-provided ones). Considering C#'s compile speed is still ridiculously fast, I suspect that might be a little bit beyond what it bothers with...

It would be interesting to examine the output IL to get some proof, though!
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0