Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How much faster would Unity games/apps be if it used C++?

Discussion in 'General Discussion' started by Arowx, Oct 26, 2013.

  1. MarigoldFleur

    MarigoldFleur

    Joined:
    May 12, 2012
    Posts:
    1,353
    It's the Mono GC for Mono 2.6. Mono 2.8 saw the new generational GC introduced, and 3.0 onward fixed most of the performance regressions that were seen elsewhere from 2.6 to 2.8. The version of Mono in Unity is currently approaching its 4th birthday.
     
  2. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    ok then we r in sync

    n that is exactly why i posted that hopefully unity will update the version of mono it uses

    not only are there number of advances, but also bug fixes

    also im not sure how hard would it be for them to decouple themselves from mono and just say some .net version whether mono or .net

    that way we could in theory run the editor and the game engine on microsoft or mono or someone else, well so long as they implemented that version of .net

    i wonder if i like removed mono what would blow up and can it be tweaked enough to run... and then how well would it run...

    i guess they could have some native dlls that do some specific things to mono and that would not work and would need to be rewritten in more generic way or have a microsoft .net version

    but i dont know if there are problems there,

    i wonder if anyone tried it and how far they got.

    i mean at some point its msil

    i even did test that worked great where i wrote a small c# library using visual studio and compiled it

    so its msil dll

    and then i put it in my test project assets and referenced it from mono c# code and it worked great

    so so long as you compile to the correct msil dll version it works for the libraries as far as i tested

    what would be braver is delete the mono runtime folder and see how far one gets.

    or perhaps another interesting test would be to try to replace the version of mono with latest and see how far one gets

    that may be easier.

    such evil thoughts :evil:
     
    Last edited: Oct 28, 2013
  3. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    There's already a pretty strong community movement to improve the quality of 3rd party assets.

    And increased dev time compared to what? Some hypothetical imaginary engine that's like Unity, only perfect in every regard? Or other packages that actually exist and also each have their own downsides?

    You're right, it doesn't change that the GC leaves much to be desired. But that in turn doesn't change the fact that there are still other solutions that that are perfectly viable (and if you really care about "low power hardware targets" then surely you especially care about avoiding unnecessary allocation instead of improved systems to clean up after you).
     
  4. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,832
    AI War.
     
  5. MarigoldFleur

    MarigoldFleur

    Joined:
    May 12, 2012
    Posts:
    1,353
    Increased dev time compared to not having to constantly refactor code specifically to avoid any potential GC hiccups. A community effort to improve third party assets doesn't mean diddly S*** when right now there's assets that haven't been updated in months or over a year in some cases. The simple fact of it is that there's a solution to the GC problem and that solution has existed for nearly three years now.
     
  6. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    So not increased dev times in comparison to, say, other engines competing with Unity?

    Refactoring code to preserve memory performance is a perfectly normal part of any performance programming. It just happens that in managed languages it's wrapped in a nice black box that we get to point at if things don't go as well as we'd like. You mentioned low powered hardware, do you really think you're getting the most of that if you're forcing a GC to clean up after you?
     
  7. MarigoldFleur

    MarigoldFleur

    Joined:
    May 12, 2012
    Posts:
    1,353
    It's not always a matter of "getting the most out of something."
     
  8. superpig

    superpig

    Quis aedificabit ipsos aedificatores? Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,206
    These appear inconsistent…?
     
  9. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    Interesting what the developer of AI Wars has to say on porting from Slim DX to Unity http://www.arcengames.com/forums/index.php?topic=8856.0

    Issues with the GC and memory limitations in mono, and also stripping back to just using the Unity rendering engine without using any GameObjects, Physics or Networking and Loading assets from file not via Unity's asset system.

    Posted July 2011, so two years on and no major progress in Unity's GC.

    PS He also talks about why he does not use C++ for game development, after moving to a C++ game engine. ;)
     
  10. raybarrera

    raybarrera

    Joined:
    Nov 20, 2010
    Posts:
    205
    24.5669% +- 1.54%
     
  11. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    Could you please include a link to your source material, stats, graphs ect? ;)
     
  12. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    4,868
    A couple years ago, I was dealing with an internal group that was wanting to dump C# and go to C++ for speed. They had looked over their code, and couldn't find anything wrong with it, and were tooling up for a rewrite. Turned out, the code in question was using a really poor algorithm (pull the entire dataset worth of work into memory, and then sort through it with LINQ). Fixing the goofup (only pulling the data they actually needed) increased their speed by a factor of 40. While I agree with many that C++ is faster, I would have to say that experience has shown me that in general, almost any language is "fast enough", and there is really little reason to move unless you really have exhausted all other options. Just moving bad algorithms from C# to C++ really accomplishes nothing.
     
  13. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    So in effect C++ can be just as slow or even slower than C# or Java. But C++ gives the programmer the control to refine and optimise the code to a much higher level than C# or Java.

    On the GC side of things note how the GC's get in the way of the optimisation effort in Java and Scala.

    Could not Unity write a C++ memory management / object pooling system that could:


    • Be designed for games, e.g. works in the Wait for Vsync time gap and/or very light per frame activity/separate thread.
    • Integrate with the GameObject classes.
    • But can be controlled by the developer.

    Let's face facts Unity runs an old version of Mono with a cranky GC.

    But to upgrade Mono Unity need to buy an expensive license from Xamarin.

    Alternatively Unity could keep the legacy Mono C# language and add C++ as an optional development language.

    Benefits: Unity C++ only games could be built as a single exe, could benefit from potential performance gains (depending on programmers) circumvent the shortcomings of C# / Mono and it's GC and potentially gain ground in the AAA space as it could allow for more advanced games from AAA C++ programmers.

    Also hybrid games could be built, where core or performance critical systems are developed in C++ and less critical scripts are developed in C#.

    So could Unity +C++ be the best of both worlds?
     
  14. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    i guess if you compare c++ to scala its no surprise c++ wins

    but if you did testing of c++ vs c#.net from microsoft on windows you would find c# is not all that bad.

    http://dada.perl.it/shootout/vc++.html
    http://dada.perl.it/shootout/csharp.html

    the prolem is that mono c# is a quite a bit behind microsoft c# .net and the version that comes with unity is even further behind...

    here take a look at some real tests where you can pick which languages you want to compare

    http://dada.perl.it/shootout/
    http://benchmarksgame.alioth.debian.org/


    re: performance

    global optimization of your code (better algorithm / data structures). and you will do just fine. and focus on readable / maintainable c# is a good language.


    re: unity

    well if they dont want to pay $$$$ for newer version of mono

    they should just take the money branch the old copy of mono they have and update the garbage collector there. if you search web you will easily find nice garbage collectors its a matter of replacing that old one. nice fun task.

    i mean microsoft licensed java and then branched it and went from there...

    i would not waste time doing c++ interface. i guess if someone wants performance that much they could license the unity source code and do c/c++

    but for indie c# is fast enough.

    also you dont have to feed the garbage collector do caching/pooling/buffering of things. not that hard to do and it will result in the garbage collector now needing to run as much

    also look at other places where you allocate and free stuff a lot and make some changes so it does not occurr as much. strings come to mind. use a string buffer to concatenate lots of string and then convert to string. instead of string = string + string all over the place.

    also do thing when game / object load do keep doing repeatedly while is running / being used.

    so get book on subject. there should be good ones for c#/.net and if not look for ones for java they booth have managed vm which similar enough workings on like strings and objects gc. that what you learn in one could apply well enough to the other.


    also get a profiler and run your code in a profiler and see what is happening. there is unity pro profiler and a bit less functional / but inexpensive unity asset store assets profilers.

    there is always profiling at c/c++ level and native .net profilers. i have a very nice free one for my amd cpu/gpu from amd that i used to profile a number of non unity games.

    so have fun with profilers...
     
    Last edited: Oct 28, 2013
  15. Gigiwoo

    Gigiwoo

    Joined:
    Mar 16, 2011
    Posts:
    2,981
    Years ago, a customer asked us to speed up our system. I took on that task and systematically went through the code and algorithms. I found the bottle necks, and reduced execution time by 94% in most places. Just by changing database queries, removing stupid loops, and tweaking code to simply be smarter. C#, C++, Java, ... it's not the language that is usually at fault.

    On the other hand, I've had engineers work for me that thought about performance with every line of code - to them, even one 'virtual' keyword was wasteful. And, in the end, they created hard to maintain code and took a long time to implement even basic things. Jonathan Blow argues this sort of 'pre-emptive optimization' drains our most expensive resource - Engineering time.

    Gigi.
     
  16. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    that is called local optimization, not good, makes very unreadable code

    what you want is global optimization algorithm level and create maintainable / readable code

    that is where the most performance gains are anyways and then you can test / maintain it...

    have them read / follow

    code complete
    http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670

    writing solid code
    http://www.amazon.com/Writing-Secure-Code-Strategies-Applications/dp/0735617228

    one of them has a very nice chart of how to write good code its like

    1. it has to be correct (do what is should do)
    2. it has to be verifyable / testable
    3. it has to be maintainable / readable
    4. it has to be globally optimized (good algorithms)

    and like at the end of the list

    10. locally optimized.

    so its like they started with number 10 which really breaks 1-3... ouch. get new programmers ;)
     
    Last edited: Oct 28, 2013
  17. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    That's my point using the classic 80/20 rule only 20% of you're code will need real optimisations, and you only find out which 20% once you have built run and profiled your code.

    So what if Unity provides the option to port your 20% performance critical code to C++ where you have more power and control to optimise it.
     
  18. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,177
    I'm never seen code that really had to be optimized but I've inlined code to make it faster and done the reverse to make it readable. Back in ancient times I designed a set of C++ templates to slip over a K&R C base code for work before I bolted for the military. When I came back over a year later I found work had taken the C++ templates and converted them all to C++ classes on 386 computers running SCO UNIX! Needless to say the store managers were complaining how slow the new code was because all of the extra function dereferencing needed to make those C++ classes work. So in-lining code does work but any manager will say forget it, it's cheaper to get me new HW.
     
  19. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    What you want is both. The idea that complex code is bad is based on the idea that inexperienced coders need to be able to work with it. If you're working on something where high performance is a requirement then there are some parts of that code where local optimisation can be incredibly important, and in those cases it's perfectly valid to draw a line in the sand and say only those with relevant experience do those parts of the work.

    Your list of priorities is indeed a good one, but not all projects should follow the same priorities. A single set of priorities can't be preached to others as some kind of global truth.

    Anyway, going back to the examples given above, a common thread there (and in almost all of the many cases of optimisation that I've heard of) is naive use of data, rather than slow operations upon the data. In such cases moving to a faster language will make no difference, because all that will do is make the execution faster, and the execution is spending most of its time waiting for data (or iterating over worthless data). This could happen both at the high level (retrieving too much irrelevant data from a DB or file) and at the low level (cache misses forcing your operations to wait for memory fetches). It's like driving down a highway where you spend most of your time stopped at a red light - will a faster car help, or are you better off looking for other solutions?
     
  20. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    The first thing that pops into my head is that almost all of that 20% will be low level engine code that Unity already handles for us under the hood. The second thing that pops into my head is that if we've got pro then we can use a C++ plugin already.

    There could well be highly specialised niche circumstances where the above aren't quite enough, but I've not run into any myself. (My crowd sim project could potentially have even more agents than it already does if it were done in C++, but I'd have to weigh that up against the costs of data marshalling. The only way to know would be to try it, and it performs well enough as is that I can't see that happening.)
     
    Last edited: Oct 28, 2013
  21. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,156
    The compiler will in-line code for you where appropriate; no need to do it manually. So you get to keep readable code and have in-lining too.

    --Eric
     
  22. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,177
    Thanks, I mainly in-lined because someone had comments spanning source files which is extremely unreadable but was allowable by the old SCO UNIX C/C++ compiler. I've personally always liked one function - one source file which was ruined a bit by C++ and these OO languages.
     
  23. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    Ugh. I'd have hated that too.

    A classic case of "just because you can do it doesn't mean you should".
     
  24. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    But I want to be able to call any plugins from the C++ side of Unity not via C# and mono. In effect I would like to have:

    [ Unity ] [ C++ ]
    [ Unity ] [ Mono ]

    With C++ we can bypass Mono and C# altogether.
     
  25. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    cant u do that already

    using c++ from visual studio you can easily write mix of managed and unmanaged code

    those dll may very well work with mono

    now if unity only has managed interface for something you can call it. you can even handle call backs by doing little wrapper to handle marshaling from managed to unmanaged code

    take a look here
    http://msdn.microsoft.com/en-us/library/aa712789(v=vs.71).aspx
    http://www.codeproject.com/Articles/1153/Mixing-Managed-and-Unmanaged-code
    http://www.cplusplus.com/forum/windows/57771/
    http://blogs.msdn.com/b/junfeng/archive/2006/05/20/599434.aspx
    http://www.windowsdevcenter.com/pub/a/dotnet/2003/01/13/intromcpp.html
    http://www.windowsdevcenter.com/pub/a/dotnet/2003/03/03/mcppp2.html
    http://blogs.msdn.com/b/abhinaba/archive/2012/11/14/c-cli-and-mixed-mode-programming.aspx

    its sort of like java jni c/c++ but easier...

    just do a little test if you dont have visual studio get visual studio express create little proof of concept test in in vc and then copy dll to unity and see if you can access from unity c# script and can that dll access the unity c# script. i mean go back and forth... it may work work. i gues depends on mono and mono should be complaint... well unless it had to be compiled with some switch

    but even then you can get unity mono and recompile it...
    https://github.com/Unity-Technologies

    i would think all the above would work with even unity indie
     
    Last edited: Oct 29, 2013
  26. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    Yes I know, but I why go through Mono at all, it seems to be part of the problem not the solution.

    Like I said direct access to Unity via C++ get's around Mono and it's issues with GC and it generally being slower than C++.
     
  27. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,156
    You still haven't demonstrated that there's actually an issue that's preventing you from doing what you want using Unity's current setup. I would even say that the current garbage collector isn't actually a real problem for most people. I do believe the flaws have been vastly over-exaggerated over time, where someone once said that it could be improved, and now it's morphed into the worst thing ever that just kills all games stone-dead and you can never ever allow any garbage to be generated ever ever ever. Which simply isn't true; even when I don't make any effort to minimize garbage I personally have never seen any actual performance problems even on mobile. I realize that I haven't tried to push Unity to the absolute limits, but then neither do most people.

    --Eric
     
  28. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    perhaps its how people do their games. i mean with just a little work you can greatly reduce need for gc

    things like caching, buffering, pooling, and like string builders should always be used where they make sense. instead of constantly instantiating / destroying which by the way is expensive even without gc involved.

    often times when applications run poorly its not the gc its because of other things. time to get a profiler and to serious start looking at ones choices, datastructues and algorithms. i bet one quickly find some poor choices and inappropriate algorithms.

    also if you look at benchmarks suites i posted link to you can see cases where c++ runs and cases where c# wins. behind it all is a nice jit so its running natively. well unless unity disabled / removed the jit. and the garbage collector you can reduce need for it by doing things that you should be doing anyways for performance reasons.


    actually if you this this garbage collector is bad, then you never used the one that early releases of java came with. back then java didnt have a jit nor did it have support for native threading and the garbage collector was pretty basic so when java finally did a garbage collection your whole java application would stop the whole time the garbage collector was running. ouch it took forever and cause problems like with socket connections. obviously the more memory you had the more little objects the longer it would take and the longer you would be roadblocked. sometime it felt like minutes went by while the garbage collector ran on just about 32mb! forget even trying anything bigger.

    still it would be nice that they fork mono and update the garbage collector on their own as best they can.
     
    Last edited: Oct 29, 2013
  29. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,832
    I Agree, I love spending huge sums of time and money optimising for something that 'seems' to be 'part of' the problem.

    Sit down, take a chill pill and listen to this smart dude:

    Optimise the 20% that is actually causing you issues, not the imagined problems.
     
  30. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    I'm in the same boat, though the way I do things typically keeps garbage to a minimum without needing to make any particular effort in that direction.

    It's not even that you can't allocate ever, it's just that you can't allocate during times when you need a stable frame rate, assuming that the GC pass will take longer than the idle time in a frame. Allocate at load times, when one-off significant changes are made (eg: character changing skins), or camera changes, or any time when the user won't notice that one frame is a few ms longer than the last.

    Aside from that, as im says, it's often a really good idea to avoid allocation and/or things that cause allocation during the periods where you need a stable frame rate anyway, and there are plenty of pretty solid strategies to manage that.
     
    Last edited: Oct 29, 2013
  31. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,177
    Avoid these problems by targeting the iPod touch 4th gen and if you have a hit you can upgrade art later with the earning for nice custom work.
     
  32. TowerOfBricks

    TowerOfBricks

    Joined:
    Oct 20, 2007
    Posts:
    962
    No it wont.

    In theory it should. But in too many cases it doesn't. Especially on 32 bit.
    At least that is what I have found when profiling code on OSX in 32bit and 64bit, both standalone and in the editor (yes I tested several times, yes I looped the testing code, yes I tried rearranging code, yes I thought about JIT warmup, nothing seemed to change the fact).

    For example, a simple trivial non-virtual property with a getter. Which will be compiled into a simple non-virtual method. This getter should be inlined.
    Code (csharp):
    1. public int stuff {
    2.    get {
    3.       return someVariable;
    4.    }
    5. }
    This will not be inlined in 32bit on OSX. It will be a bit slower, how much depends on the datatype, but it could be as much as 50-60% slower.
    On 64-bit it is inlining this code correctly, but other simple getters it does not inline.

    On a related note, the Unity API implementation could definitely be speed up with simple fixes like inlining the getter methods. This is especially important when the type is a large struct like Vector3, Matrix4x4 or Bounds.
    For example the bounds implementation could be substantially improved in some cases: http://forum.unity3d.com/threads/204243-Slow-Unity-Math-Please-Unity-Tech-keep-core-math-fast

    One very annoying case of this inlining is index getters, like those used for List<T>[index]
    However I am not totally sure if it is a valid optimization to inline a getter like the below
    to work directly with the data in the array instead of copying the Vector3 and returning it.
    Code (csharp):
    1. public Vector3 Stuff {
    2.    get {
    3.       return someArray[0];
    4.    }
    5. }
    In a usage context like
    Code (csharp):
    1.  int mystuff = Stuff.x + 2;
    I.e it is only reading the value, not setting it anywhere.

    That things like the above are not inlined have consequences like working with a Vector3[] is about 2 times faster than with a List<Vector3> because of the index operation copying the Vector3 all the time. Trust me, this is not something to be ignored. I actually had to change my implementation of a vector-calculation-heavy algorithm to use Vector3[] instead of List<Vector3> and saw a substantial improvement in framerate.


    My results:
    * Getter for int, double, string is 2-3 times slower than a field on 32-bit. Properly inlined in 64bit.
    * Getter for slightly more complex code (e.g doing a bitwise AND with some constant) has similar results on 32 and 64 bit.
    * Getter for a large struct, like Vector3 or Matrix4x4 is a lot slower on 32-bit and just quite a lot slower on 64-bit.
    calling .isIdentity on a Matrix4x4 property (which was an identity matrix, but that doesn't matter much) on 32-bit can be up to 5 times slower than calling it on a field. On 64-bit it takes slightly less than twice as long time with a property versus a field.

    In case anyone want to test this themselves, here are is all the data and code.

    Profiling code: http://pastebin.com/Wc9adp2A
    Profiling class which is required for the above code (basically a fancy timer): http://pastebin.com/bVdtyxBd

    Raw results 64-bit standalone:
    Code (csharp):
    1. Fields 0.3 ms avg: 0.32 ms avg mem: 0 bytes
    2. Props 0.3 ms avg: 0.30 ms avg mem: 0 bytes
    3. Fields Complex 0.5 ms avg: 0.46 ms avg mem: 0 bytes
    4. Props Complex 0.5 ms avg: 0.46 ms avg mem: 0 bytes
    5. Fields Large Struct 1.7 ms avg: 1.72 ms avg mem: 0 bytes
    6. Props Large Struct 3.1 ms avg: 3.10 ms avg mem: 0 bytes
    Raw results 32-bit (editor)
    Code (csharp):
    1. Fields 0.7 ms avg: 0.69 ms avg mem: 0 bytes
    2. Props 2.5 ms avg: 2.54 ms avg mem: 0 bytes
    3. Fields Complex 0.7 ms avg: 0.72 ms avg mem: 0 bytes
    4. Props Complex 2.7 ms avg: 2.66 ms avg mem: 0 bytes
    5. Fields Large Struct 3.0 ms avg: 3.01 ms avg mem: 0 bytes
    6. Props Large Struct 15.3 ms avg: 15.29 ms avg mem: 0 bytes
     
  33. im

    im

    Joined:
    Jan 17, 2013
    Posts:
    1,393
    c# compiler is not as fancy as c++ optimizing compiler when it comes to optimizations

    also keep in mind that mono c# compiler is not microsoft c# compiler

    and that the version of mono c# that comes with unity is quite old!

    here is what micorosoft does (who knows what the version that comes with unity actually does)

    and remember this is for 64 bit one!

    http://www.hanselman.com/blog/Relea...dCMethodInliningInReleaseBuildCallStacks.aspx

    still a number of things could easily be done manually and its good to do them anyways... so optimizer cleaning behind programmer.

    so if you search web for optimizing c# you will find some nice ways to optimize your code without making it unreadable / unmaintainable, which you should not ever do for the sake of local optimizations....

    also better to use better algorithms and not have things in loop that dont need to be in loop and that maybe very expensize like

    Transform transform = this.GetComponent<Transform>();

    how why would you want the above in a loop when its not dependent on what is being iterated in the loop. better to take it out and best to put it in like Start() since it really needs to be done ones, so there is no need to have it lets say in Update()
     
    Last edited: Oct 31, 2013
  34. trooper

    trooper

    Joined:
    Aug 21, 2009
    Posts:
    673
    Lol, I remember trying to use Carmack's Square root hack (i know he didn't invent it... keyboard warriors) via a C++ DLL (and a Objective-C plugin), it was back when I didn't know any better... the extra overhead killed what I was trying to do.
     
  35. CarterG81

    CarterG81

    Joined:
    Jul 25, 2013
    Posts:
    1,737
    I'm pretty sure 99.99% of the arguments "C++ vs C#" which include the assumption that "C++ is better, faster, stronger...*Million Dollar Man Sound Effect Leap*" is simply people who have no idea what they're talking about and know very little about programming software.

    People whine and squeak about "improving performance" but the amount of performance you'll see in C++ compared to C# is more or less non-existent. You might get better performance in C++, but it will be so little compared to the power of modern hardware that it doesn't make a difference. You might also get WORSE performance in C++ than in C#. Sometimes because of worse programming, sometimes because C# actually is faster sometimes as a language.

    What really actually matters?

    Performance - Whether or not the player experiences poor or great performance. The language you use won't be why. It will be either how it's programmed, the user's hardware limitations, or the user's software problems.

    Game Completion Speed- Want to talk about fast? C# is a lot faster than C++. When it comes to speed of code completion. In fact, some of the simplest tasks in C++ require you to use a third party library and make multiple classes just to provide the right functionality. C# can do these things in a single line of code. C++ programmers can spend endless hours chasing down memory leaks because they made an error with their pointers. C# doesn't allow this error in the first place.

    Non-Professionals- Why do you need C++? You don't have the expertise to even know how to get better performance. You're more likely to get WORSE performance.

    What is your task? Are you working low level? No. You're working very high level, with Game Engines like Unity3D. If you're not using a game engine, you still want to work at a high level. What in your game requires such low level programming that you need C++? Is it so significant of a performance issue, that you can't use C# to fix the problem the same way?



    No offense, but if you change languages because your game start load times change from 8.36745 seconds in C#, to 8.12682 seconds in C++, then you're an idiot for it.

    Honestly, I'd like to hear big AAA companies' reasons for switching their native language to C++. I'd be surprised if it had to deal with performance, not something like marketing, accessibility, industry standardization, or portability.
     
    Last edited: Nov 4, 2013
  36. CarterG81

    CarterG81

    Joined:
    Jul 25, 2013
    Posts:
    1,737
    To support my claim of 99.99% ignorance, and how wrong people are to think C++ is better (because it is not, it's actually worse except in rare circumstances) here is a link to a good answer on the same question on StackOverflow.

    http://stackoverflow.com/questions/138361/how-much-faster-is-c-than-c

     
  37. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    It's simple, in a game and if the play timespace is in real time, then ideally you need everything to happen in < 16ms for 60+ fps. Now with C# you have overheads and optimisations that are out of your control.

    But if you do need more oomph, you can try:


    1. Profile and optimise your code (which you should already have done)
    2. Re-Design your code to work around the problem (e.g. pre-calculation, lookup tables or faster but less accurate formulas)
    3. Call an external C++ dll, (allow for invocation overhead, probably best for batch processes on a separate thread)
    4. Drop in the SIMD mono extensions, (and gain access to your CPU's number crunching features. if available on your platform)
    5. Launch a thread (with the complexity overhead and debugging headaches)
    6. Write a DirectCompute solution (learning a whole new language and subsystem. Only for DX11 systems)

    Now consider you're not using C# your using C++, it has been around for ages and used extensively in game engines there are probably some great libraries or tricks and tips that you can utilise to blow away your problem, as someone else has already solved it.

    People keep saying if your C# coding is slow why would your C++ code be any faster, and we have argued about different performance benchmarks and tests found online which is good (although the test in question was a chinese to english dictionary system which is fine if you're writing a text based adventure or translating your game).

    But my point is, it's probably not going to be all my own code, I am going to find that snippet, library or function online that does it in a fraction of the time my code does it and as long as it passes my tests plug it in and get it working.

    And with C++ I can drag in assembly language sub-routines, GPU libraries and even multi-threaded CPU/GPU sdk's, or I could drag in a totally different physics engine, GUI's, Voxel engines ect.

    I think you could really open up the full potential of Unity with the addition of the C++ language, I know it's not for everyone and that's why it would be in addition to mono.

    But think of a future version of Unity. You're hitting performance problems with your game, it's dropping to 20-30fps and not giving you that 60fps you need. You run the profiler and Unity let's you know that one of your frequently used C# scripts is causing the bottleneck and would you like Unity to convert it to C++ and include it in the games core. You click yes it converts and compiles the code and you re-run the game. Wow you're game is now running at 60-120fps. Isn't Unity great!
     
  38. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    25,844
    But your bottleneck is usually not the actual language :p Most games are GPU not CPU bound.


    Have you made a game which is CPU bound from your scripts, ie is script execution > 16ms in the profiler? if so, look at the algorithms used, the technique. It would likely be only a tiny percent faster in C++. C++ is subject to the same bad algorithms as C# is - basically you could use GameObject.Find for an item based off the name, or you could use a Dictionary and get it in very little time. Do you know how to use Dictionary in C++? It's called std::map and it's a little difficult to use in comparison.


    You need to do a lot more work in C++ and usually you will need to use a similar optimisation technique as C#. Where C++ shines are with pointers and data structures, things that benefit engine development and shifting huge amounts of data around with memcpy. These aren't typically ever used in game logic.


    Do not forget, that AAA does use lua and other scripting languages for the 'logic' ie gameplay, with C++ for lower level engine work - pretty much exactly what Unity is doing.


    By all means add C++. It just won't make a shred of difference except for increasing development times and perhaps, moving someone's crappy script from taking 10ms to 8ms. Or it might make their crappy script (as we're assuming they're crap) take 15ms and leak memory.


    I understand where you are coming from, and certainly, having a path for C++ would be interesting for many people. I'm not sure it's the magic bullet though.

    For me, the greatest optimisation Unity could do is optimising what is there already. A better GC. A better Mono.
     
    Last edited: Nov 16, 2013
  39. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    What about obfuscation, just watched the Unite talk on securing your games (here) and it looks like any game released with Unity also releases the source code. With compiled C++ at least it would be a bit harder to obtain the source code of the games. Regardless of how crappy our or their scripting is if it works then it's worth something.

    All I'm saying is that at the moment we don't, well unless you purchase a source license, have the option to build a standalone game using C++ and Unity.

    From a hobbyists/small indies perspective C# is great up to a point, but it has problems and issues the GC and Mono performance issues. Would C++ allow developers to bypass these problem areas completely, and would it make Unity a better option for professional game developers?

    Think of the game utilities that could be added to Unity using C++, all those pro libraries, tools and technologies could be ported and added, e.g. physics, rendering, music, networking, GUI and AI.
     
  40. Ocid

    Ocid

    Joined:
    Feb 9, 2011
    Posts:
    476
    I don't think C++ is the magic bullet you think its going to be. The above scenario as well isn't necessarily going to produce faster code either. Every possibility its going to end up slower the C# code you wrote. You certainly won't see a 3-4x increase in performance.

    As hippo pointed out many AAA studios don't use C++ or similar for gameplay logic. They use scripting languages.
     
  41. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,832
    Except that you're wrong - you can build a standalone game using C++ and Unity. If you have IP that you wish to obfuscate than you *can* do this. Some very powerful plugins to Unity (e.g. browsers, or scaleform) are written primarily in C++ IIRC.
     
  42. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    OK but I'm betting that all those scripting systems are doing is directing the the main game mechanics engine written in C++, the scripts will not be dealing with low level details like transforms, physics and maths they will driving game entities behavioural responses in the game.

    Yes you can build a plugin to Unity using C++ but I thought that means you still need Mono in the mix to transfer the information and would therefore have to drive your game via C#.

    E.G. If you're in game vehicle hit's something, Unity generates an OnCollisionEvent, this would be passed into Mono, and you would have to have code in place to take the information and pass it into your plugin. So you end up writing a Unity C# to C++ interface.

    However in a direct C++ to Unity interface you would just have to write a single layer to interact directly with Unity.

    Found this language performance page, best bit is it has graphs near the bottom of the page and he uses Mono 2.10 sgen. http://attractivechaos.github.io/plb/

    So I'm going to go with the heuristic that C++ is about 2-3 times faster than C#, unless UT or anyone else can write a simple game in Unity in C# and C++ and compare the performance.

    And lets not forget that Mono's JIT compilation adds to the bane of all gameplayers the loading time of your game.
     
  43. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,156
    It doesn't really do that at all.

    No you can't; Unity doesn't work like that. You're asking for a completely different engine, in which case why are you using Unity? (BTW, the word is "etc.", which is short for "et cetera".)

    --Eric
     
  44. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    Which, aside from your odd usage of "mechanics engine", is exactly how it works here too. The scripts do typically high-level things and change properties that direct what the game engine does under the hood. Physics is a great example - you'll apply some forces or change a property, which sets some data which PhysX handles in the next physics tick in under-the-hood code most likely written in C++, C or perhaps even platform-specific assembly.

    Also, you've mentioned events, which makes this a great time to point out that in the grand scheme of a game engine events almost never happen. Unless you're doing something with them that's both blocking and insanely expensive (which is a little silly, to say the least) they really shouldn't impact your performance. Events are raised when something might have to change. A change is potentially made in response. The engine under the hood then continues doing its fast thing with the changed information. Regardless of how they're implemented the event code is almost always excruciatingly slow compared to the under the hood stuff, because it does one off things (really slow) where the under-the-hood stuff batches things, uses tight loops, and has its data laid out for optimum operation speed (really fast). This is why plenty of game engines get away with scripting engines which are much slower than Mono. The types of things you do in event scripts simply aren't the things worth optimising. Why optimise something that gets run once every few seconds, maybe, when you could optimise something that happens hundreds of thousands of times per second?

    Code that runs in the game loop (Update() et al.) is a different story, but it's best practice to keep that to a minimum and disable stuff you're not using. Turn components on in response to the appropriate event and have them turn themselves off when they're done. Only a minority should be running at any given time, and the only ones that are always running should be ones dealing with user input and things like that (oddly enough, this is stuff that deals with, wait for it... a constant stream of events). And then we're in similar territory to before - why optimise the stuff that barely ever happens?

    When I say "optimise" here I of course count moving to a faster language as an optimisation.

    Whether a language/runtime environment is faster or not is a very different question to whether it would make your game run faster or not.
     
  45. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    To be honest, it sounds like there's some misunderstanding as to what libraries, SDKs, APIs and so on actually are, and/or how they're integrated with software.
     
  46. lazygunn

    lazygunn

    Joined:
    Jul 24, 2011
    Posts:
    2,749
    I'll admit i know nearly bugger all about all this but i dont see the relevance of pushing c++ when upgrading mono is a far more relevant issue? Maybe that's hoo haa, but yes i don't think the reality of developing stuff in c++ means faster code, in fact, as said, the cost of paying good programmers to create and maintain good code would be exorbitant (your currency per hour times overhead doing stuff the long way round vs a few lines and forget about it)
     
  47. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148
    I thought Unity uses Mono a JIT compiler based on .Net. You write C# or Javascript and it is converted to a CLI and when you game runs the CLR takes the CLI and converts it to assembly to run on your machine?

    Yes Unity can be used like that, there is nothing stopping a developer regardless of language from using Unity as little more than a rendering layer and passing meshes and materials to it. For example Arcen games AI War (written in C#) ported from SlimDX to Unity and in the process did not use a lot of the Unity features, e.g. GameObjects, Physics, Networking instead they used the lower level mesh rendering system in Unity.
     
  48. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    12,180
    First of all not on all platforms, and second, it does not significantly increase "bane of all gameplayers the loading time of your game" by any noticeable amount

    Sure, but you don't just "drag in" these things and head off. Doing that for a port is one thing, doing it for a ground-up game is quite another. For starters it'll kill most of the advantage that the editor gives you, which you may note isn't a big deal when porting, but is a huge deal if you're using Unity for the tools it provides (and really... what else would you use it for if you're not porting?). Like Eric says, if you want to do that then you may as well just roll your own engine, because that's virtually what you're doing anyway.

    In short, yes, it's technically possible but not something you'd do in the majority of practical scenarios.
     
  49. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    7,148

    C# Unity code
    Code (csharp):
    1.  
    2.     void Update()
    3.     {
    4.  
    5.  
    6.         float h = Input.GetAxis("Horizontal") * scrollSpeed;
    7.         float v = Input.GetAxis("Vertical") * scrollSpeed;
    8.         float d = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    9.  
    10.  
    11.         Vector3 mousePos = Input.mousePosition;
    12.  
    Equivalent C++ Unity code
    Code (csharp):
    1.  
    2.     void Update()
    3.     {
    4.  
    5.  
    6.         float h = Input.GetAxis("Horizontal") * scrollSpeed;
    7.         float v = Input.GetAxis("Vertical") * scrollSpeed;
    8.         float d = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    9.  
    10.  
    11.         Vector3 mousePos = Input.mousePosition;
    12.  
    But it would take a bit longer to compile and run.
     
  50. lazygunn

    lazygunn

    Joined:
    Jul 24, 2011
    Posts:
    2,749
    You've employed a programmer for 30 seconds to write a high level input scenario. So does that relate to the rest of your game? That example was asinine at best.