321

Or is it now the other way around?

From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself.

Thought any of you could explain these differences in detail or point me to the right place for information on this.

5
  • 9
    Protected, to prevent any more random benchmarks from being posted. If you think you can make your case, you will need 10 rep to do so. Commented May 10, 2011 at 18:13
  • 1
    It's almost a moot question, given that we live in an age in which IL can be converted to CPP and optimized from there: docs.unity3d.com/Manual/IL2CPP.html
    – pixelpax
    Commented Apr 2, 2018 at 17:22
  • A language that checks for out of range array access will never outperform one that doesn't. Commented Mar 3, 2020 at 22:02
  • @SevaAlekseyev It's not the language who does this but the compiler. One of the reasons C++ is that fast (apart from the obvious ones) is that C++ compilers have been around for past 35 years (if not more). There's nothing that prevents C# compilers to get better over time. For the case you mention, please read this stackoverflow.com/questions/16713076/…
    – Trap
    Commented Mar 4, 2020 at 10:42
  • I once wrote a blackjack card counting simulator in C# and then ported it to C++. Performance was identical. I haven't used C++ for anything since then except an ffmpeg/libav-backed video player that outputs to a Direct3D swapchain panel embedded in a WinUI app. Also, performance of the C++-based UWP/WinUI's is horrible compared to the C#-based WPF. I think because it was C++ they decided they didn't have to think about performance, while the WPF C# devs did things like minimizing boxing and countless other optimizations. Commented Jun 21 at 22:10

29 Answers 29

418

There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the really cool ones are only arriving just now.

So C++ is faster, in many cases. But this is only part of the answer. The cases where C++ is actually faster, are highly optimized programs, where expert programmers thoroughly optimized the hell out of the code. This is not only very time consuming (and thus expensive), but also commonly leads to errors due to over-optimizations.

On the other hand, code in interpreted languages gets faster in later versions of the runtime (.NET CLR or Java VM), without you doing anything. And there are a lot of useful optimizations JIT compilers can do that are simply impossible in languages with pointers. Also, some argue that garbage collection should generally be as fast or faster as manual memory management, and in many cases it is. You can generally implement and achieve all of this in C++ or C, but it's going to be much more complicated and error prone.

As Donald Knuth said, "premature optimization is the root of all evil". If you really know for sure that your application will mostly consist of very performance critical arithmetic, and that it will be the bottleneck, and it's certainly going to be faster in C++, and you're sure that C++ won't conflict with your other requirements, go for C++. In any other case, concentrate on first implementing your application correctly in whatever language suits you best, then find performance bottlenecks if it runs too slow, and then think about how to optimize the code. In the worst case, you might need to call out to C code through a foreign function interface, so you'll still have the ability to write critical parts in lower level language.

Keep in mind that it's relatively easy to optimize a correct program, but much harder to correct an optimized program.

Giving actual percentages of speed advantages is impossible, it largely depends on your code. In many cases, the programming language implementation isn't even the bottleneck. Take the benchmarks at http://benchmarksgame.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all.

29
  • 115
    <quote>code in interpreted languages gets faster in later versions of the runtime</quote> As code compiled by a better version of the compiler will also get faster. Commented Sep 26, 2008 at 9:44
  • 55
    In fact there is at least one reason: JIT needs to be fast, and cannot afford to spend time on various advanced optimizations available to a C++ compiler. Commented Sep 26, 2008 at 14:04
  • 74
    "but also commonly leads to errors due to over-optimizations." [citation desperately needed]. I work at a national lab, and we optimize the hell out of our code. This does not commonly result in buggy code. Commented Dec 11, 2008 at 13:52
  • 42
    "It's relatively easy to optimize a correct program, but much harder to correct an optimized program."
    – gradbot
    Commented Jul 17, 2010 at 16:33
  • 22
    Inge: not sure you're on the right track there. Yes, C# is implemented in another language, but the JIT compiler is generating machine code, so it's not an interpreted language. Thus it is not limited by its C++ implementation. I'm not quire sure why you think adding some manager to something inherently makes it faster. Commented Jan 26, 2013 at 12:59
150

I'm going to start by disagreeing with part of the accepted (and well-upvoted) answer to this question by stating:

There are actually plenty of reasons why JITted code will run slower than a properly optimized C++ (or other language without runtime overhead) program including:

  • compute cycles spent on JITting code at runtime are by definition unavailable for use in program execution.

  • any hot paths in the JITter will be competing with your code for instruction and data cache in the CPU. We know that cache dominates when it comes to performance and native languages like C++ do not have this type of contention, by design.

  • a run-time optimizer's time budget is necessarily much more constrained than that of a compile-time optimizer's (as another commenter pointed out)

Bottom line: Ultimately, you will almost certainly be able to create a faster implementation in C++ than you could in C#.

Now, with that said, how much faster really isn't quantifiable, as there are too many variables: the task, problem domain, hardware, quality of implementations, and many other factors. You'll have run tests on your scenario to determine the the difference in performance, and then decide whether it is worth the the additional effort and complexity.

This is a very long and complex topic, but I feel it's worth mentioning for the sake of completeness that C#'s runtime optimizer is excellent, and is able to perform certain dynamic optimizations at runtime that are simply not available to C++ with its compile-time (static) optimizer. Even with this, the advantage is still typically deeply in the native application's court, but the dynamic optimizer is the reason for the "almost certainly" qualifier given above.

--

In terms of relative performance, I was also disturbed by the figures and discussions I saw in some other answers, so I thought I'd chime in and at the same time, provide some support for the statements I've made above.

A huge part of the problem with those benchmarks is you can't write C++ code as if you were writing C# and expect to get representative results (eg. performing thousands of memory allocations in C++ is going to give you terrible numbers.)

Instead, I wrote slightly more idiomatic C++ code and compared against the C# code @Wiory provided. The two major changes I made to the C++ code were:

  1. used vector::reserve()

  2. flattened the 2d array to 1d to achieve better cache locality (contiguous block)

C# (.NET 4.6.1)

private static void TestArray()
{
    const int rows = 5000;
    const int columns = 9000;
    DateTime t1 = System.DateTime.Now;
    double[][] arr = new double[rows][];
    for (int i = 0; i < rows; i++)
        arr[i] = new double[columns];
    DateTime t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);

    t1 = System.DateTime.Now;
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            arr[i][j] = i;
    t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);
}

Run time (Release): Init: 124ms, Fill: 165ms

C++14 (Clang v3.8/C2)

#include <iostream>
#include <vector>

auto TestSuite::ColMajorArray()
{
    constexpr size_t ROWS = 5000;
    constexpr size_t COLS = 9000;

    auto initStart = std::chrono::steady_clock::now();

    auto arr = std::vector<double>();
    arr.reserve(ROWS * COLS);

    auto initFinish = std::chrono::steady_clock::now();
    auto initTime = std::chrono::duration_cast<std::chrono::microseconds>(initFinish - initStart);

    auto fillStart = std::chrono::steady_clock::now();

    for(auto i = 0, r = 0; r < ROWS; ++r)
    {
        for (auto c = 0; c < COLS; ++c)
        {
            arr[i++] = static_cast<double>(r * c);
        }
    }

    auto fillFinish = std::chrono::steady_clock::now();
    auto fillTime = std::chrono::duration_cast<std::chrono::milliseconds>(fillFinish - fillStart);

    return std::make_pair(initTime, fillTime);
}

Run time (Release): Init: 398µs (yes, that's microseconds), Fill: 152ms

Total Run times: C#: 289ms, C++ 152ms (roughly 90% faster)

Observations

  • Changing the C# implementation to the same 1d array implementation yielded Init: 40ms, Fill: 171ms, Total: 211ms (C++ was still almost 40% faster).

  • It is much harder to design and write "fast" code in C++ than it is to write "regular" code in either language.

  • It's (perhaps) astonishingly easy to get poor performance in C++; we saw that with unreserved vectors performance. And there are lots of pitfalls like this.

  • C#'s performance is rather amazing when you consider all that is going on at runtime. And that performance is comparatively easy to access.

  • More anecdotal data comparing the performance of C++ and C#: https://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=gpp&lang2=csharpcore

The bottom line is that C++ gives you much more control over performance. Do you want to use a pointer? A reference? Stack memory? Heap? Dynamic polymorphism or eliminate the runtime overhead of a vtable with static polymorphism (via templates/CRTP)? In C++ you have to... er, get to make all these choices (and more) yourself, ideally so that your solution best addresses the problem you're tackling.

Ask yourself if you actually want or need that control, because even for the trivial example above, you can see that although there is a significant improvement in performance, it requires a deeper investment to access.

19
  • 18
    @Quonux thank you for the comment. Of course this is not a "real program". The point of the benchmarks was refactor a C# benchmark offered elsewhere on this page as evidence that JITted code is somehow faster than native--it's not, and the benchmark was potentially misleading to new people.
    – U007D
    Commented Mar 9, 2017 at 0:44
  • 10
    @Quonux why do you have to write like that? It's people like you that makes me dislike stackoverflow. Commented Jul 20, 2017 at 21:03
  • 5
    @MarkusKnappenJohansson I had a bad day ;) , I'm just a human too, removed my downvote, yet my opinion still applies. Oh please don't dislike SO just because there are some "stupid" people :) . Have a nice one.
    – Quonux
    Commented Jul 22, 2017 at 17:17
  • 17
    COMPLETELY MISLEADING BENCHMARK. In C++ version you are simply reserving part of memory (and then marveling how that operation takes microseconds to execute). In C# version you are creating 5000 ARRAYS (instantiating objects in memory). C++ is faster than C#... but difference is nowhere near 40%... right now it's more in range of <10%. What your example illustrates is that programmers should stick with language of their choice (and from your profile it's obvious that you are career C++ programmer). In C# you can do 2D array int[,]... following up with example.
    – nikib3ro
    Commented Dec 27, 2017 at 17:52
  • 4
    From what I can tell, the code in your C++ example is literally just allocating the memory ahead of time. The PROPER C# implementation would simply write 'List<double> arrs = new List<double>(ROWS*COLS)' which allocates the memory required to index a 2 dimensional array in 1 dimensional format (eg, what you did in C++). There's absolutely no reason to allocate a 2-dimensional array and manually flatten it -- the massive amount of iterations in your pre-test is the cause of the shitty performance. I imagine the overhead would still be more in C#, but not by a considerable amount.
    – Jax
    Commented Jul 7, 2018 at 1:42
99

It's five oranges faster. Or rather: there can be no (correct) blanket answer. C++ is a statically compiled language (but then, there's profile guided optimization, too), C# runs aided by a JIT compiler. There are so many differences that questions like “how much faster” cannot be answered, not even by giving orders of magnitude.

2
  • 224
    Have you got any evidence to support your outrageous five oranges claim? My experiments all point to 2 oranges at most, with a 3 mango improvement when doing template metaprogramming.
    – Alex
    Commented Jan 2, 2010 at 8:59
  • 2
    Agreed, I am getting 2 oranges as well based on my calculations, I am not seeing any mangoes though.
    – Sushant
    Commented Aug 24, 2022 at 18:45
68

In my experience (and I have worked a lot with both languages), the main problem with C# compared to C++ is high memory consumption, and I have not found a good way to control it. It was the memory consumption that would eventually slow down .NET software.

Another factor is that JIT compiler cannot afford too much time to do advanced optimizations, because it runs at runtime, and the end user would notice it if it takes too much time. On the other hand, a C++ compiler has all the time it needs to do optimizations at compile time. This factor is much less significant than memory consumption, IMHO.

9
  • 6
    In one project at work we had to mine gargantuan amounts of data, including holding many GB in memory simultaneously and performing expensive calculations on all of it -- this required precise control of all allocations, C++ was pretty much the only choice. +1 for C++. On the other hand, that was just one project, we spent most of our time writing systems which interacted with slow simulators, and debugging could be a nightmare, so I wished we could have used a programmer-time-optimizing language for all that other stuff.
    – Bogatyr
    Commented Sep 9, 2011 at 10:24
  • 7
    @IngeHenriksen: I am well aware of the Dispose pattern, but it does not help with the managed memory at all. Commented Jan 21, 2013 at 18:21
  • 10
    @IngeHenriksen disposing it only ensures that the Dispose method has been called. Disposal never frees garbage collected memory. The Dispose method is only intended for cleaning up unmanaged resources like file handles and has nothing to do with memory management.
    – doug65536
    Commented Jan 29, 2013 at 17:52
  • 1
    @NemanjaTrifunovic: "JIT compiler cannot afford too much time to do advanced optimizations". Can you cite some optimizations that are not done by JITs because they would take too long?
    – J D
    Commented Nov 2, 2013 at 16:53
  • 6
    @user3800527: Even if adding RAM was always feasible (and it is not - imagine Microsoft adding RAM to each MS Office user) that will not solve the problem. Memory is hierarchical and a C# program will have many more cache misses than a C++ one. Commented Apr 13, 2016 at 12:58
39

One particular scenario where C++ still has the upper hand (and will, for years to come) occurs when polymorphic decisions can be predetermined at compile time.

Generally, encapsulation and deferred decision-making is a good thing because it makes the code more dynamic, easier to adapt to changing requirements and easier to use as a framework. This is why object oriented programming in C# is very productive and it can be generalized under the term “generalization”. Unfortunately, this particular kind of generalization comes at a cost at run-time.

Usually, this cost is non-substantial but there are applications where the overhead of virtual method calls and object creation can make a difference (especially since virtual methods prevent other optimizations such as method call inlining). This is where C++ has a huge advantage because you can use templates to achieve a different kind of generalization which has no impact on runtime but isn't necessarily any less polymorphic than OOP. In fact, all of the mechanisms that constitute OOP can be modelled using only template techniques and compile-time resolution.

In such cases (and admittedly, they're often restricted to special problem domains), C++ wins against C# and comparable languages.

29
  • 6
    Actually, Java VMs (and probably .NET) go to great lengths to avoid dynamic dispatch. Basically, if there is a way to avoid polymorphims, you can be pretty sure your VM will do it. Commented Sep 29, 2008 at 14:21
  • 3
    +1 I always have trouble explaining this to my C# colleagues who know little C++ in a way that would enable them to appreciate the significance. You've explained it rather nicely. Commented Sep 15, 2010 at 0:33
  • 9
    @crtracy: you are making your bet without high-performance computing applications. Consider weather forecasting, bioinformatics and numeric simulations. The performance lead of C++ in these areas will not shrink, because no other code can achieve comparable performance at the same level of high abstraction. Commented Sep 16, 2010 at 13:24
  • 5
    @Jon Apples and oranges. Your specific claim was “C# is orders of magnitude faster than C++ in the context of metaprogramming”, not “using precompiled code is orders of magnitude faster than interpreted code”. While we’re at it, your claim that runtime code generation is “more general” than compile-time code generation is also clearly wrong – they both have strengths and weaknesses. Compile-time code generation uses the type system to provide static type safety – runtime code generation cannot do that (it can provide strong type safety, but not static type safety). Commented Nov 5, 2013 at 15:10
  • 6
    @user3800527 I think you’re missing the whole point of this answer. Of course you can work around this by breaking encapsulation and dropping down to low-level structures — you can write assembly in (most) any language. The thing that makes C++ (almost) unique, and uniquely suited for high-performance programming, is that you can build high-level abstractions that come at no runtime cost. So you don’t need to write assembly-like code in C++ to get premium performance: a well-written sort(arr, generic_comparer) will be as efficient as a hand-written loop in C++. It never will be in C#. Commented Apr 14, 2016 at 15:07
21

C++ (or C for that matter) gives you fine-grained control over your data structures. If you want to bit-twiddle you have that option. Large managed Java or .NET apps (OWB, Visual Studio 2005) that use the internal data structures of the Java/.NET libraries carry the baggage with them. I've seen OWB designer sessions using over 400 MB of RAM and BIDS for cube or ETL design getting into the 100's of MB as well.

On a predictable workload (such as most benchmarks that repeat a process many times) a JIT can get you code that is optimised well enough that there is no practical difference.

IMO on large applications the difference is not so much the JIT as the data structures that the code itself is using. Where an application is memory-heavy you will get less efficient cache usage. Cache misses on modern CPUs are quite expensive. Where C or C++ really win is where you can optimise your usage of data structures to play nicely with the CPU cache.

1
  • Worked for Cadence Design systems 2010 2013, on a large code base dating back 1989 or so, linux desktop application. Had tremendous gains investigating and fixing for months issues related to cache and page defaults. And the fine granularity of control c++ gives you is the tool to achieve this. Also figured out we had a 2x slowdown when migrating to x64 systems, fixed later, same type of issue : usage of pointers and registry in the cpu cache. C++ was truely unbeatable, perhaps RUST is now too abe to do the same thing. Commented Aug 30, 2022 at 2:38
19

For graphics the standard C# Graphics class is way slower than GDI accessed via C/C++. I know this has nothing to do with the language per se, more with the total .NET platform, but Graphics is what is offered to the developer as a GDI replacement, and its performance is so bad I wouldn't even dare to do graphics with it.

We have a simple benchmark we use to see how fast a graphics library is, and that is simply drawing random lines in a window. C++/GDI is still snappy with 10000 lines while C#/Graphics has difficulty doing 1000 in real-time.

9
  • 5
    I was intrigued by your answer. Have you tested the same benchmark with unsafe code and lockbits, and drawing the random lines yourself? Now that would be an interesting thing to look at.
    – Pedery
    Commented Jun 10, 2012 at 23:02
  • 2
    @Pedery nope I haven't. just using the GDI and .NET.Graphics in the most basic of ways. what do you mean by "drawing the random lines yourself"?
    – QBziZ
    Commented Jul 3, 2012 at 8:20
  • 1
    Then you should perhaps consider to test this to get a more realistic metrics for how fast C# can be. Here's a nice overview of the technique: bobpowell.net/lockingbits.htm
    – Pedery
    Commented Jul 10, 2012 at 14:33
  • 6
    That is not what we want to do, putting separate pixels in a frame buffer ourselves. If you have to implement everything yourself what's the point of having an API/Platform to code against? For me this is a non-argument. We never needed to put separate pixels in a framebuffer in GDI for drawing lines, and we are not planning to do this in .NET neither. In my view, we did use a realistic metric, and .NET turned out to be slow.
    – QBziZ
    Commented Jul 18, 2012 at 12:07
  • 1
    Well, I have just a slight idea what blob detection is, but just stating one timing does rather prove nothing at all. Have you written one in C++? In JavaScript? And compared those to the one in C#? And besides that, I don't think blob detection is using many graphics primitives. Correct me if wrong, but I guess it's statistical algorithms performing operations on pixels.
    – QBziZ
    Commented Apr 17, 2016 at 10:07
14

The garbage collection is the main reason Java# CANNOT be used for real-time systems.

  1. When will the GC happen?

  2. How long will it take?

This is non-deterministic.

11
  • 5
    I'm not a huge Java fan but there's nothing that says Java can't use a real-time friendly GC.
    – Zan Lynx
    Commented Apr 1, 2010 at 6:47
  • 5
    There are plenty of real-time GC implementations if you care to look. (GC is an area that is overflowing with research papers)
    – Arafangion
    Commented May 19, 2010 at 0:37
  • FWIW, Richard Jones just published an updated version of his garbage collection book that covers, amongst other things, state-of-the-art real-time GC designs.
    – J D
    Commented Sep 7, 2011 at 8:01
  • 12
    This is a nonsense argument, Windows (and Linux) are not Real Time OSes. Your C++ code could be swapped out for a number of 18 ms slots at any time too. Commented May 17, 2014 at 8:47
  • 2
    @HenkHolterman True, but you could always write a boot-loader in assembly, tie that into a kernel bootstrap for your application and execute your C++ apps directly against the hardware (in RT btw). You can't do this in C# and any efforts that I have seen only mimic pre-compiled assembly in C# and use a ton of C code, which make it point-less to use C#. Reading all this is kinda funny, because C# is truly useless without the .NET framework. Commented Jan 12, 2016 at 6:54
14

C/C++ can perform vastly better in programs where there are either large arrays or heavy looping/iteration over arrays (of any size). This is the reason that graphics are generally much faster in C/C++, because heavy array operations underlie almost all graphics operations. .NET is notoriously slow in array indexing operations due to all the safety checks, and this is especially true for multi-dimensional arrays (and, yes, rectangular C# arrays are even slower than jagged C# arrays).

The bonuses of C/C++ are most pronounced if you stick directly with pointers and avoid Boost, std::vector and other high-level containers, as well as inline every small function possible. Use old-school arrays whenever possible. Yes, you will need more lines of code to accomplish the same thing you did in Java or C# as you avoid high-level containers. If you need a dynamically sized array, you will just need to remember to pair your new T[] with a corresponding delete[] statement (or use std::unique_ptr)—the price for the extra speed is that you must code more carefully. But in exchange, you get to rid yourself of the overhead of managed memory / garbage collector, which can easily be 20% or more of the execution time of heavily object-oriented programs in both Java and .NET, as well as those massive managed memory array indexing costs. C++ apps can also benefit from some nifty compiler switches in certain specific cases.

I am an expert programmer in C, C++, Java, and C#. I recently had the rare occasion to implement the exact same algorithmic program in the latter 3 languages. The program had a lot of math and multi-dimensional array operations. I heavily optimized this in all 3 languages. The results were typical of what I normally see in less rigorous comparisons: Java was about 1.3x faster than C# (most JVMs are more optimized than the CLR), and the C++ raw pointer version came in about 2.1x faster than C#. Note that the C# program only used safe code—it is my opinion that you might as well code it in C++ before using the unsafe keyword.

Lest anyone think I have something against C#, I will close by saying that C# is probably my favorite language. It is the most logical, intuitive and rapid development language I've encountered so far. I do all my prototyping in C#. The C# language has many small, subtle advantages over Java (yes, I know Microsoft had the chance to fix many of Java's shortcomings by entering the game late and arguably copying Java). Toast to Java's Calendar class anyone? If Microsoft ever spends real effort to optimize the CLR and the .NET JITter, C# could seriously take over. I'm honestly surprised they haven't already—they did so many things right in the C# language, why not follow it up with heavy-hitting compiler optimizations? Maybe if we all beg.

2
  • 4
    "you will just need to remember to pair your new T[] with a corresponding delete[]" – No you don't. There's std::unique_ptr to do that for you.
    – Emil Laine
    Commented Dec 29, 2015 at 1:11
  • asuming you wrote something in graphics why write safe code in c#, have you considered using unsafe code and compare again ?.
    – Peter
    Commented Apr 12, 2016 at 6:53
11

As usual, it depends on the application. There are cases where C# is probably negligibly slower, and other cases where C++ is 5 or 10 times faster, especially in cases where operations can be easily SIMD'd.

2
  • Best case for VMs will be run-time compilation of generated code (e.g. to match a regular expression read in at run time) because statically compiled vanilla C++ programs can only use interpretation because they do not have a JIT compiler built in.
    – J D
    Commented Sep 6, 2011 at 20:13
  • 1
    Note from the future: .NET does have support for SIMD and friends since about 2014, though it's not widely used.
    – Luaan
    Commented Jul 14, 2016 at 8:29
11

We have had to determine if C# was comparable to C++ in performance and I wrote some test programs for that (using Visual Studio 2005 for both languages). It turned out that without garbage collection and only considering the language (not the framework) C# has basically the same performance as C++. Memory allocation is way faster in C# than in C++ and C# has a slight edge in determinism when data sizes are increased beyond cache line boundaries. However, all of this had eventually to be paid for and there is a huge cost in the form of non-deterministic performance hits for C# due to garbage collection.

2
  • 2
    In C++, you have the option of using different allocation methods, so depending on how memory was allocated (AOT?) in C#, it could be done the same way (but much faster) in C++. Commented Jan 12, 2016 at 6:56
  • 5
    @zackery.fix .NET has an interesting edge in heap allocation, because it only has to move a pointer to allocate a new object. This is only feasible due to the compacting garbage collector. Of course you can do the same thing in C++, but C++ doesn't do that. It's funny how you use the same argument to say "C# could but doesn't, so it's garbage" and "C++ doesn't, but it could, so it's awesome" :)
    – Luaan
    Commented Jul 14, 2016 at 8:27
10

I know it isn't what you were asking, but C# is often quicker to write than C++, which is a big bonus in a commercial setting.

1
  • 2
    I'd say it's quicker most of the time :)
    – Trap
    Commented Sep 26, 2008 at 21:29
8

> From what I've heard ...

Your difficulty seems to be in deciding whether what you have heard is credible, and that difficulty will just be repeated when you try to assess the replies on this site.

How are you going to decide if the things people say here are more or less credible than what you originally heard?

One way would be to ask for evidence.

When someone claims "there are some areas in which C# proves to be faster than C++" ask them why they say that, ask them to show you measurements, ask them to show you programs. Sometimes they will simply have made a mistake. Sometimes you'll find out that they are just expressing an opinion rather than sharing something that they can show to be true.

Often information and opinion will be mixed up in what people claim, and you'll have to try and sort out which is which. For example, from the replies in this forum:

  • "Take the benchmarks at http://shootout.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all."

    Ask yourself if you really understand what "these largely test arithmetic code" means, and then ask yourself if the author has actually shown you that his claim is true.

  • "That's a rather useless test, since it really depends on how well the individual programs have been optimized; I've managed to speed up some of them by 4-6 times or more, making it clear that the comparison between unoptimized programs is rather silly."

    Ask yourself whether the author has actually shown you that he's managed to "speed up some of them by 4-6 times or more" - it's an easy claim to make!

2
  • I couldn't agree with you more and that's the reason why I asked in this forum... After all, the answers have to be somewhere, haven't they? :)
    – Trap
    Commented Sep 26, 2008 at 21:39
  • 1
    Yes. The answer is "It depends.".
    – user49117
    Commented Dec 29, 2008 at 22:49
7

For 'embarassingly parallel' problems, when using Intel TBB and OpenMP on C++ I have observed a roughly 10x performance increase compared to similar (pure math) problems done with C# and TPL. SIMD is one area where C# cannot compete, but I also got the impression that TPL has a sizeable overhead.

That said, I only use C++ for performance-critical tasks where I know I will be able to multithread and get results quickly. For everything else, C# (and occasionally F#) is just fine.

6

.NET languages can be as fast as C++ code, or even faster, but C++ code will have a more constant throughput as the .NET runtime has to pause for GC, even if it's very clever about its pauses.

So if you have some code that has to consistently run fast without any pause, .NET will introduce latency at some point, even if you are very careful with the runtime GC.

17
  • 9
    -1: This is actually a myth. Firstly, the latency of idiomatic C++ is actually awful and often much worse than .NET because RAII causes avalanches of destructors when large data structures fall out of scope whereas modern GCs are incremental and .NET's is even concurrent. Secondly, you can actually completely remove GC pauses on .NET by not allocating.
    – J D
    Commented Sep 6, 2011 at 20:09
  • 2
    If you do this, you then have to forego using the BCL as most of the methods create transient objects. Commented Sep 7, 2011 at 8:52
  • 6
    This is quite true, it wasn't until .net 4 that the GC was made incremental. We have a large C# app that pauses for seconds at a time for GC. For performance critical apps this is a killer.
    – Justin
    Commented Nov 10, 2011 at 22:32
  • 5
    There's a reason why programs that tend to push the hardware tend to use C++. You have more fine tuned control when you need it. Performance is only key when you're pushing the system, otherwise use C# or Java to save you time. Commented Oct 30, 2012 at 13:51
  • 6
    if you can't manage the cache behavior, you can't beat optimized c++ code. A cache miss from L1 to main memory could slow your operation 100 times.
    – DAG
    Commented Mar 17, 2016 at 5:20
4

In theory, for long running server-type application, a JIT-compiled language can become much faster than a natively compiled counterpart. Since the JIT compiled language is generally first compiled to a fairly low-level intermediate language, you can do a lot of the high-level optimizations right at compile time anyway. The big advantage comes in that the JIT can continue to recompile sections of code on the fly as it gets more and more data on how the application is being used. It can arrange the most common code-paths to allow branch prediction to succeed as often as possible. It can re-arrange separate code blocks that are often called together to keep them both in the cache. It can spend more effort optimizing inner loops.

I doubt that this is done by .NET or any of the JREs, but it was being researched back when I was in university, so it's not unreasonable to think that these sort of things may find their way into the real world at some point soon.

4

Applications that require intensive memory access eg. image manipulation are usually better off written in unmanaged environment (C++) than managed (C#). Optimized inner loops with pointer arithmetics are much easier to have control of in C++. In C# you might need to resort to unsafe code to even get near the same performance.

4

It's an extremely vague question without real definitive answers.

For example; I'd rather play 3D-games that are created in C++ than in C#, because the performance is certainly a lot better. (And I know XNA, etc., but it comes no way near the real thing).

On the other hand, as previously mentioned; you should develop in a language that lets you do what you want quickly, and then if necessary optimize.

10
  • 4
    Could you name a few examples? Games written in C# what you've found slow
    – Karl
    Commented Sep 26, 2008 at 14:10
  • 1
    Even the example applications that came with the installation felt slow. Commented Sep 30, 2008 at 5:35
  • 10
    The garbage collector is a huge liability in making games with C#, as it can kick in any time, causing major pauses. Explicit memory management ends up being easier for game development. Commented Oct 30, 2008 at 22:44
  • 4
    Most modern games are GPU-limited. For such games it does not matter if the logic (executed on CPU) is 10% slower, they are still limited by GPU, not CPU. Garbage collector is a real problem, causing random short freezes if the memory allocations are not tuned well. Commented Nov 26, 2008 at 18:05
  • 2
    @postfuturist: That is not true on PC; the garbage collector does such a good job of getting in and out I've never experienced any problems with it. However, on XBox 360 and Zune/Windows-7-Phone, the garbage collector is not nearly as smart as on PC; I've never written for either, but people who have tell me the garbage collector is a huge problem. Commented Jun 1, 2011 at 22:06
3

I've tested vector in C++ and C# equivalent - List and simple 2d arrays.

I'm using Visual C#/C++ 2010 Express editions. Both projects are simple console applications, I've tested them in standard (no custom settings) release and debug mode. C# lists run faster on my pc, array initialization is also faster in C#, math operations are slower.

I'm using Intel Core2Duo [email protected], C# - .NET 4.0.

I know that vector implementation is different than C# list, but I just wanted to test collections that I would use to store my objects (and being able to use index accessor).

Of course you need to clear memory (let's say for every use of new), but I wanted to keep the code simple.

C++ vector test:

static void TestVector()
{
    clock_t start,finish;
    start=clock();
    vector<vector<double>> myList=vector<vector<double>>();
    int i=0;
    for( i=0; i<500; i++)
    {
        myList.push_back(vector<double>());
        for(int j=0;j<50000;j++)
            myList[i].push_back(j+i);
    }
    finish=clock();
    cout<<(finish-start)<<endl;
    cout<<(double(finish - start)/CLOCKS_PER_SEC);
}

C# list test:

private static void TestVector()
{

    DateTime t1 = System.DateTime.Now;
    List<List<double>> myList = new List<List<double>>();
    int i = 0;
    for (i = 0; i < 500; i++)
    {
        myList.Add(new List<double>());
        for (int j = 0; j < 50000; j++)
            myList[i].Add(j *i);
    }
    DateTime t2 = System.DateTime.Now;
    Console.WriteLine(t2 - t1);
}

C++ - array:

static void TestArray()
{
    cout << "Normal array test:" << endl;
    const int rows = 5000;
    const int columns = 9000;
    clock_t start, finish;

    start = clock();
    double** arr = new double*[rows];
    for (int i = 0; i < rows; i++)
        arr[i] = new double[columns];
    finish = clock();

    cout << (finish - start) << endl;

    start = clock();
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            arr[i][j] = i * j;
    finish = clock();

    cout << (finish - start) << endl;
}

C# - array:

private static void TestArray()
{
    const int rows = 5000;
    const int columns = 9000;
    DateTime t1 = System.DateTime.Now;
    double[][] arr = new double[rows][];
    for (int i = 0; i < rows; i++)
        arr[i] = new double[columns];
    DateTime t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);

    t1 = System.DateTime.Now;
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            arr[i][j] = i * j;
    t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);

}

Time: (Release/Debug)

C++

  • 600 / 606 ms array init,
  • 200 / 270 ms array fill,
  • 1sec /13sec vector init & fill.

(Yes, 13 seconds, I always have problems with lists/vectors in debug mode.)

C#:

  • 20 / 20 ms array init,
  • 403 / 440 ms array fill,
  • 710 / 742 ms list init & fill.
10
  • 1
    I'd love to see index accessor in std::list. Anyway, it takes 37 secs with list, release mode. Release without debugging: 3s list, 0,3 s vector. Probably dereferencing issue or sth. Sample: nopaste.pl/12fb
    – Wiory
    Commented Jun 23, 2011 at 15:48
  • 2
    For more precise measurements you shouldn't be using System.DateTime.Now, but rather, the Stopwatch class.
    – Sam
    Commented Aug 24, 2014 at 23:17
  • 4
    Part of the reason you are getting such slow fill times for the vector in C++ is you are using push_back. This has been shown on numerous posts to be slower than using the at method or operator []. In order to use either of those methods you need to use the resize or reserve method. Additionally, the reason your initialization is taking so long for c++ vector case is that you are forcing a copy or assignment operator [not sure which in this case) to initialize your c++ vector. For the array in c++ there is an algorithm that uses 2 new calls rather than 5001 and is faster iterating as well. Commented Nov 15, 2014 at 9:55
  • 6
    I think you didn't do c++ in a appropriate way. Just a glance and found so many issues. E.g. vector<vector<double>> myList=vector<vector<double>>()
    – DAG
    Commented Mar 17, 2016 at 2:44
  • 3
    Wow. Not sure what conclusions one can draw from comparing Lists versus resizable arrays, but if you're going to use vectors like this, you'll want to learn about reserve(), my friend, reserve().
    – U007D
    Commented Sep 7, 2016 at 20:56
3

I would put it this way: programmers who write faster code, are the ones who are the more informed of what makes current machines go fast, and incidentally they are also the ones who use an appropriate tool that allows for precise low-level and deterministic optimisation techniques. For these reasons, these people are the ones who use C/C++ rather than C#. I would go as far as stating this as a fact.

2
  • Notch coded minecraft to be pretty fast considering the amount of data he's manipulating. Also, he coded it mostly single-handedly in a comparatively short amount of time, something that would have been virtually impossible in C++. I do agree with the optimization techniques though--if you have the extra 10x dev time to spend so your code runs twice as fast, it's probably worth it.
    – Bill K
    Commented Mar 1, 2018 at 23:21
  • @BillK Maybe he lost a valuable amount of time writing convoluted code to work around the limitations of C#. I wouldn't take a 10x devtime / 2x runtime speed ratio for granted. Commented May 20 at 8:32
3

If I'm not mistaken, C# templates are determined at runtime. This must be slower than compile time templates of C++.

And when you take in all the other compile-time optimizations mentioned by so many others, as well as the lack of safety that does, indeed, mean more speed...

I'd say C++ is the obvious choice in terms of raw speed and minimum memory consumption. But this also translates into more time developing the code and ensuring you aren't leaking memory or causing any null pointer exceptions.

Verdict:

  • C#: Faster development, slower run

  • C++: Slow development, faster run.

3

I found this April 2020 read: https://www.quora.com/Why-is-C-so-slow-compared-to-Python by a real-world programmer with 15+ years of Software Development experience.

It states that C# is slower usually because it is compiled to Common Intermediate Language (CIL) instead of machine code like C++. The CIL is then put through Common Language Runtime (CLR) which outputs machine code. However, if you keep executing C# it will take the output of the machine code and cache it so the machine code is saved for the next execution. All in all, C# can be faster if you execute multiple times since it is in machine code after multiple executions.

There is also comments that a good C++ programmer can do optimizations that can be time consuming that will in end be optimized.

2
  • C# isnt slower than python. I made a simple test program that creates a 1024*1024*8 sized byte array and then fills it with index % 255 and it took 1.4 seconds in python and 45ms in C# (first execution, not after running it multiple times) - also the question was how much faster C++ is, not python Commented Apr 13, 2022 at 9:04
  • Quora answers consist of many opinions but very little real knowledge. Python performance is not even close to that of C#, C++, or any compiled language. Furthermore, whatever author described the "reason" for the perceived performance difference does not understand how intermediate compilation works, nor that Python does something somewhat similar. Commented Nov 15, 2022 at 17:33
2

I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors. In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.

2

Well, it depends. If the byte-code is translated into machine-code (and not just JIT) (I mean if you execute the program) and if your program uses many allocations/deallocations it could be faster because the GC algorithm just need one pass (theoretically) through the whole memory once, but normal malloc/realloc/free C/C++ calls causes an overhead on every call (call-overhead, data-structure overhead, cache misses ;) ).

So it is theoretically possible (also for other GC languages).

I don't really see the extreme disadvantage of not to be able to use metaprogramming with C# for the most applications, because the most programmers don't use it anyway.

Another big advantage is that the SQL, like the LINQ "extension", provides opportunities for the compiler to optimize calls to databases (in other words, the compiler could compile the whole LINQ to one "blob" binary where the called functions are inlined or for your use optimized, but I'm speculating here).

4
  • 2
    Any proper C++ developer will not run into the problems you describe. Only bad C programmers who decided to slap classes on their programs and call it C++ have those problems.
    – Clearer
    Commented Jan 3, 2018 at 8:42
  • 1
    for the love of gods, this is 8 years old, OMFGz
    – Quonux
    Commented Jan 8, 2018 at 20:28
  • feel free to give a better more up to date answer
    – Quonux
    Commented Jan 8, 2018 at 20:29
  • We should also consider the compile-time metaprogramming capability of c++ which enables developers to execute pieces of code at compile time. Note modern c++ is more like C with templates. It's more towards functional programming compared to OOPS. The introduction of constexp had made metaprogramming easier to read and write.
    – user982042
    Commented May 6, 2021 at 18:43
2

There are some major differences between C# and C++ on the performance aspect:

  • C# is GC / heap based. The allocation and GC itself is overhead as the non locality of the memory access
  • C++ optimizer's have become very good over the years. JIT compilers cannot achieve the same level since they have only limited compilation time and don't see the global scope

Besides that programmer competence plays also a role. I have seen bad C++ code where classes where passed by value as argument all over the place. You can actually make the performance worse in C++ if you don't know what you are doing.

2

One area that I was instrumenting code in C++ vs C# was in creating a database connection to SQL Server and returning a resultset. I compared C++ (Thin layer over ODBC) vs C# (ADO.NET SqlClient) and found that C++ was about 50% faster than the C# code. ADO.NET is supposed to be a low-level interface for dealing with the database. Where you see perhaps a bigger difference is in memory consumption rather than raw speed.

Another thing that makes C++ code faster is that you can tune the compiler options at a granular level, optimizing things in a way you can't in C#.

1

> After all, the answers have to be somewhere, haven't they? :)

Umm, no.

As several replies noted, the question is under-specified in ways that invite questions in response, not answers. To take just one way:

And then which programs? Which machine? Which OS? Which data set?

3
  • I fully agree. I wonder why people expect a precise answer (63.5%), when they ask a general question. I don't think there is no general answer to this kind of question. Commented Nov 24, 2008 at 23:54
  • @callmesteve: I know what you mean, but your last sentence should sound like nails over a chalk board to any programmer. Commented Nov 6, 2010 at 8:52
  • 1
    This doesn't appear to answer the question, and reads more as a comment or rant.
    – Tas
    Commented Jun 17, 2016 at 0:20
1

It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.

I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.

#include "stdafx.h"

using namespace System;
using namespace System::Diagnostics;

bool EqualMe(String^ first, String^ second)
{
    return first->Equals(second);
}
int main(array<String ^> ^args)
{
    Stopwatch^ sw = gcnew Stopwatch();
    sw->Start();
    for (int i = 0; i < 100000; i++)
    {
        EqualMe(L"one", L"two");
    }
    sw->Stop();
    Console::WriteLine(sw->ElapsedTicks);
    return 0;
}
-14

Inspired by this, I did a quick test with 60 percent of common instruction needed in most of the programs.

Here’s the C# code:

for (int i=0; i<1000; i++)
{
    StreamReader str = new StreamReader("file.csv");
    StreamWriter stw = new StreamWriter("examp.csv");
    string strL = "";
    while((strL = str.ReadLine()) != null)
    {
        ArrayList al = new ArrayList();
        string[] strline = strL.Split(',');
        al.AddRange(strline);
        foreach(string str1 in strline)
        {
            stw.Write(str1 + ",");
        }
        stw.Write("\n");
    }
    str.Close();
    stw.Close();
}

String array and arraylist are used purposely to include those instructions.

Here's the c++ code:

for (int i = 0; i<1000; i++)
{
    std::fstream file("file.csv", ios::in);
    if (!file.is_open())
    {
        std::cout << "File not found!\n";
        return 1;
    }

    ofstream myfile;
    myfile.open ("example.txt");
    std::string csvLine;

    while (std::getline(file, csvLine))
    {
        std::istringstream csvStream(csvLine);
        std::vector csvColumn;
        std::string csvElement;

        while( std::getline(csvStream, csvElement, ‘,’) )
        {
            csvColumn.push_back(csvElement);
        }

        for (std::vector::iterator j = csvColumn.begin(); j != csvColumn.end(); ++j)
        {
            myfile << *j << ", ";
        }

        csvColumn.clear();
        csvElement.clear();
        csvLine.clear();
        myfile << "\n";
    }
    myfile.close();
    file.close();
}

The input file size I used was 40 KB.

And here's the result -

  • C++ code ran in 9 seconds.
  • C# code: 4 seconds!!!

Oh, but this was on Linux... With C# running on Mono... And C++ with g++.

OK, this is what I got on Windows – Visual Studio 2003:

  • C# code ran in 9 seconds.
  • C++ code – horrible 370 seconds!!!
8
  • 8
    You're using different data structures and library code there, although "370 seconds" does indicate something horrible - you aren't running it in the debugger by any chance are you? I suspect that the performance of the CSV library you are using is more interesting than the performance of the language you are using. I would question the use of a vector in that context, and what optimisations you used. Additionally, it is widely known that iostreams (in particular, the "myfile << *j << ", ";") is much slower than other methods of writing to the file, for at least some common implementations.
    – Arafangion
    Commented May 18, 2010 at 3:14
  • 6
    Finally, you're doing more work in the C++ version. (Why are you clearing the csvColumn, csvElement and csvLines?)
    – Arafangion
    Commented May 18, 2010 at 3:14
  • 3
    Every iteration of the while loop is going to destruct and reconstruct a std::istream and a std::vector and a std::string. The while body goes out of scope every iteration, all those variables inside the while scope are going to destruct and construct on every iteration.
    – doug65536
    Commented Jan 29, 2013 at 18:45
  • 3
    from the looks of reading your c++ code you are trying to copy from one file to another file. Instead of using the complex interactions between file streams, strings, vectors and string streams, you could have just copied the input file stream to the output file stream. This would have saved a lot of time and memory. Commented Nov 15, 2014 at 10:13
  • 3
    to do speed tests, test things in memmory dont get to disk IO, unsless your testing on the latest SSD's and its dedicated to your performance app. As computers constantly write to disk, even if you dont touch the keyboard.
    – Peter
    Commented Apr 12, 2016 at 6:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.