Thursday, May 6, 2010

Why C# is better than C++

I could phrase this as "why I hate C++" or "why C++ sucks", but let's try the more positive spin, "why C# is better". The reasons are so numerous and compelling that there is only one reason to use C++ instead, and that is better performance.
  1. C# compiles much faster
  2. IntelliSense is much more reliable and faster (press F12 in Visual Studio to see the definition of any symbol)
  3. Automatic memory management cuts your development time in half all by itself - not just because you write less code, but also because you'll never have to track down "double free" problems and you'll very rarely have memory leaks (and if do you have memory leaks, CLR profiler can help track them down)
  4. No weird errors caused by #include order or #defines
  5. No more buffer overflows or other C-related security vulnerabilities
  6. Debugging is much easier; you can execute arbitrary expressions and call your own functions and properties from within Visual Studio's debugger (and SharpDevelop, I expect)
  7. Strings are handled the same way in all code (no more converting between various string representations)
  8. C# has anonymous inner functions with type inference (but the newest version of C++ has so-called "lambdas" too)
  9. GUIs are easier to make in C# (at least if you use WinForms. I found WPF very hard to learn)
  10. LINQ (Language INtegrated Query)
  11. "yield return" statement for writing generators and coroutines (approximate C equivalent)
  12. You can create and compile code at run-time using Reflection.Emit, Dynamic Methods or (easiest) LambdaExpression.Compile. These use the JIT engine to produce new machine code at run-time.
  13. The .NET standard libraries ("BCL") have more capabilities than those of C++, and the STL is more cumbersome (object->my_vector.erase(object->my_vector.begin() + index), anyone?)
  14. Unlike C++ templates, C# generics are guaranteed to work for all type parameters, do not bloat your code size, and can be used by modules linked dynamically (mind you, C++ templates can do some things that are hard/impossible for generics, but advanced use of templates is difficult)
  15. The MS C# compiler gives much better error messages than the MS C++ compiler
  16. You can mix different programming languages much more easily in .NET. Bjarne Stroustrup said, "I consider the idea of one language, one programming tool, as the one and only best tool for everyone and for every problem infantile"--yet C++ isn't designed to inter-operate with any language other than C. You can use SWIG if necessary, but it's got a big learning curve and C++ can't take credit for it anyway. On Windows, COM is a possible solution, but it's a huge pain to write COM classes in C++.
  17. There are various tools for analyzing and modifying .NET assemblies/programs after they are compiled, e.g. PostSharp provides aspect-oriented programming and Microsoft Code Contracts let you specify preconditions, postconditions and invariants in your classes.
  18. You can easily see how the standard libraries work in their binary form, using Reflector (the source code of the BCL is also available).
  19. You can write "safe" code that can run directly in a web browser (Silverlight)
  20. It is possible to write a C# program that targets a mobile device (ARM) and run the same binary on your desktop PC
  21. You'll no longer have to manage *.h files and write every function declaration twice. Well, you can save yourself work by leaving short"inline" functions in the header file, but you'll pay for it later with slower compile times.

    The need to use a different syntax for member functions in the header file than the implementation is a huge pet peeve of mine. Consider the difference between the header file declaration "virtual std::string Name(bool longForm = false);" and the cpp file equivalent "string ClassName::Name(bool longForm) { ... }". In C++ I'm expected to manually remove "virtual", "= false" and the semicolon, but add "ClassName::". Plus you might want to remove "std::" if you're "using namespace std" in the cpp file. Doing all this a few dozen times in a day can drive me mad, and of course the two copies make maintenance harder too.
  22. Dynamic linking and reflection make it easy to support plug-in architectures, and to use 3rd party libraries without compiling them yourself.
  23. No more dependency-detection glitches where you change a struct or virtual function table but not all dependencies are recompiled, leading to bizarre and unpredictable run-time behavior. In C# I never see such glitches, and if they did happen you would get a run-time exception rather than weird crashes or strange behavior.
  24. C# IDEs support automatic refactoring and Visual C# underlines syntax and semantic errors as soon as you make them. No such luck in C++!
Unfortunately, I still have to use C++! It is still the performance king and the standard on Windows platforms, and I maintain a performance-critical project for WinCE, on which .NET performs poorly.

Some say C# is slower, but I find that if you write code carefully (more like you would in C), you can make C# almost as fast as C. The Microsoft .NET JIT compiler does not optimize nearly as well as a C compiler, but I find that C# code generally runs faster than a debug build of equivalent C/C++ code.

Unfortunately, whereas C++ code may be 20 times slower when it runs on mobile (ARM-based) devices compared to a desktop PC, C# on the Compact Framework seems to be closer to 100 times slower than the same C# code running on a desktop PC. Microsoft needs to put a lot more work into their ARM version! Also note that Compact Framework has fewer features (e.g. no support for run-time code generation).

Update: Long after writing this blog post I made a C++ vs C# benchmark. The conclusions were exactly as I expected/feared: C# is often almost as fast as C++ (but about half as fast in certain cases), while the Compact Framework is 3-11 times slower than C++.

Now as much as I hate C++, and prefer C# over Java, the .NET Framework is far from perfect. Some parts of the BCL were badly designed, and by now it is getting to be extremely bloated. Also, I think the .NET framework needs some new features. Chief among my requests would be Go-style slices and interfaces, and return type covariance (of course). This would bring a lot of C's big-fiddling prowess to C# without compromising type safety. You know, that deserves its own blog entry.

18 comments:

Anonymous said...

C# is a managed language. And a managed language won't never be faster than a native one. You're comparing speed with a native language like C++ is a joke.
C# is good for business application but C++ is good for scientific, engineer app. If you tell me you will use C# to write a compiler, a OS, or even AutoCad or Photoshop, I'm going to laugh so hard. Any language has its own use. You hate C++ because you just don't get it. C++ is harder to learn, require much more dedication and thought, but it's super powerful.

Qwertie said...

No, I use C++ all the time. I have used template specialization and partial specialization, boost libraries, operator overloading, exceptions, references, you name it. I have written a custom memory manager, pixel-by-pixel graphics algorithms, high performance C++ code, and even inline assembly way back in the day. My criticisms of it come entirely from experience. C++ is powerful but has a lot of disadvantages. It would be possible to have a language with all of C++'s power but none of the disadvantages I mentioned, but that language has not yet been created. C# and Go are excellent competitors to C++, and of course good compilers HAVE been written in C#.

Anonymous said...

yea true C# is better but if you consider the high performance applications,platform Independence context ,scientific,military projects the best selections in C++ since C# is controlled by Microsoft once the company fallen down whole developer set will be kicked from their job as well it is same for Java as well but C++ doesn't have an owner so there is no risky about learning that.

C++ GUI programming is awful with Win32 or even MFC but u can still use Wxwidget or QT whatever u want 3rd party library that makes ur work easy.

the languages fight will never end as I think but if u want to write business applications probably u should have ability to write them faster so the selection is either Java or C# but if u want much more advance programs apart from business context then use C or C++./

Qwertie said...

No, C# will not disappear even if Microsoft does. Open-source implementations (Mono, gmcs) would live on, and probably Microsoft Visual Studio would too (the creditors wouldn't let MS's IP assets go to waste).

I've used QT a bit and it's clearly superior to MFC, and to be fair the internals of .NET WinForms are bloated and of questionable design quality, but the ease-of-use is terrific, and seem better than QT on the whole (but IIRC, I had to do my signals and slots by hand, is there a WinForms-like designer for QT?)

I don't see why C# should be limited to "business apps". I don't see why it wouldn't be a good choice for writing graphics apps, games, or non-business websites. You may have to write certain algorithms in C++, but when C# offers so many benefits I would want to use it for all the high-level code.

There is one thing I would miss from C++ and that is its highly flexible templates, which I have used heavily in my C++ code. On the other hand, I suspect all my templates are a major part of the reason my code compiles slowly. Also, templates are much more awkward to use than necessary (A problem that wouldn't exist if the C++ guys had designed a proper metaprogramming system like FOG, http://www.computing.surrey.ac.uk/research/dsrg/fog/)

A asshole came in here to insult me today, but he posted the same thing five times and the spam filter kicked in. Anyway, he said "C# compiles much faster - this does not necessarily make the 'language' better in any way". No, it does make C# better. C++ compilers are heavily optimized in C++, while a C# compiler WRITTEN IN C# is faster. The reason is the faulty language design of C++, where it re-compiles every header file and every template class in every .cpp file. Even with precompiled headers, my C++ code compiles quite slowly (the PCH is over 50 MB so I imagine it takes some time to load). This fact is perhaps the #1 reason why the Go language exists.

Anonymous said...

An Ignored Blog.! lol
what a failure.

Anonymous said...

Hi
Useful Blog Qwertie, thanks!

IlikeBothCsharpAndCplusplus said...

"I have used template specialization and partial specialization, boost libraries, operator overloading, exceptions, references,"

I must say that as a C++ developer myself, that did not make much sense if I put into perspective that you are a also a seasoned C++ developer. "Used template specialization and partial specialization"... what does that even mean? I know the concepts themselves, they apply to generic programming, but that by itself does not mean anything in your sentence. "Operator overloading, exceptions, references"... no seasoned C++ developer would put those things as a 'proof' to say 'I use C++ all the time'.

It sounded like a bunch of nonsense that you grabbed from google by typing 'Advanced C++ concepts'.

I develop in both C++ and C# and both are good languages and have their own merits.

Also, I'd like to point out (since you pointed it out), the reason intellisense is so bad is not because it's for `C++` but because Microsoft wants to push C#. Look at the project properties page for C# and compare it to C++. There is no reason for C++ page to look like garbage and be a pain in the ass to work with. Check out Visual Assist and how incredibly fast/reliable intellisense can be for C++. Microsoft has their own agenda for producing subpar intellisense for C++.

Weird errors by #include? Really? I am now certain you are not a seasoned C++ dev as you claimed.

Buffer overflows is one of the reasons C++ and C will always be faster at heavy operations simply because they do not perform these checks. If you want to check buffer overflows, by all means, create a class and do so (std::vector?).

"Automatic memory management cuts your development time in half all by itself" I guess you never heard of RAII.

"Debugging is much easier; you can execute arbitrary expressions and call your own functions and properties from within Visual Studio's debugger" Again, Microsoft wants to push C#. Check out some commercial (yes, expensive) tools for C++ debugging/performance analysis.

"Strings are handled the same way in all code" Sure, I agree that for someone who doesn't want to deal with this, it is a great time-saver (again to my point, use the language which suits best for your project).

Agree on the point about anonymous functions.

Advanced used of templates is difficult is like saying Calculus is difficult. Yes it is difficult but if mastered can produce results C# generics never can.

Agreed with point regarding maintenance of declaration/definition. Tools have been developed to make it easier/faster. Visual Assist for example can define the function for you with a simple shortcut.

Also, do you go by the name of ziggy? Think carefully before you answer...

Anonymous said...

Qwertie! you sir are a class A DUMBASS!!!

Anonymous said...

I can understand saying C# is better than C++ for some jobs. I can even understand saying you prefer C# over C++. But saying that one language is better than the other, as an absolute? Each has their pros and cons.

I will say that C++'s compatibility with C, while it does help C students make the transition, did give C++ some of C's bad features.

Anonymous said...

different languages, different purposes. c# is better for RAD and higher reliability applications. But C++ performance and memory usage are still far superior. constantly comparing the two is idiotic.

Anonymous said...

"different languages, different purposes. c# is better for RAD and higher reliability applications. But C++ performance and memory usage are still far superior. "

- I agree with this.

"constantly comparing the two is idiotic"

this is no more idiotic than the rest of us who read and commented this blog

i think the comparison of various languages over the past have actually led to the ones we see today - features were compared between different languages and eventually new versions of those languages implemented features /concepts they found desireable from other languages.

i have no issues with Qwertie comparing languages, but must also agree that he sounds like someone throwing advanced c++ topics he googled to make it appear as if he can legimately compare the two languages.

Anonymous said...

@Anonymous August 31, 2010 12:54 PM

Let me know the name of the engineering shop uses such an unsafe technology as C++ so I can warn others about it.

Anonymous said...

> Advanced used of templates is difficult is like saying Calculus is difficult. Yes it is difficult but if mastered can produce results C# generics never can.

Well aside from C++ template metaprogramming, there's nothing particularly special about C++ templates over C# or Java generics. There are situations where template metaprogramming can come in handy, such as with checking units in calculations. But languages like C#, unlike C++, can actually be parsed. Writing external static analysis tools for checking units is trivial in non-C++ languages, which means C++ metaprogramming is by and large useless outside C++.

Anonymous said...

hey friends , someone plz suggest me company name, that they change development lang... and now finally they are satisfied with c#

Unknown said...

Can't agree any more. though I admit C++ is powerful, has its use and has its reputation as the most complicated language on the planet, I have to maintain aside from what the author has mentioned that C# is by far a language that is much more pragmatic, encourages better programming practice and design and is much easier to refactor and review all achieved with its reasonable and better than average runtime performance.

MuThink said...

People who think C++ code is far better than C# and C# is just for business apps, better be careful, as their bosses might not like being misled. C# is far better in many cases, even apps like Photoshop, AutoCAD, etc. would be better off written in C#.
I started programming in C in 1986 (before I used Assembly language) and worked for Digital Research as a junior engineer in 1987. I have been programming ever since then. I have been using C++ since 1991. Although initially skeptical of C#, I am now a full convert. I believe anything which can be programmed in C# should be programmed in C#. (I also like F# and functional languages as well, which can be much better than C# even, in terms of making maintainable code.)
I also write high-performance code and after programming hundreds of hours of my own performance test and comparing the output of optimized C++ versus C#, I have come to the conclusion that almost everything should be programmed in C#, even critical code sections. The code produced by the JIT compiler, in many cases was just as fast or nearly as fast as that produced by the optimized C++ compiler. Only in some cases are some full-featured .NET containers significantly less efficient than their STL counterparts. In those cases, I recommend just to use some other container, rather than switch to C++.

There are only 4 legitimate excuses NOT to use C# for everything:
1. Your platform does not support it (even the mac and android support some form of C#.) Kernel mode device drivers simply cannot be written in C#.
2. Installation size matters a lot (although many distros of .NET and mono exist which are small.)
3. The compact framework just won't cut it (it is a lot slower than native code.)
4. Life or death deterministic computation speed is needed (like in a rocket ship.)The garbage collector, although very well-designed still can cause occasional threads to pause in extreme cases (You can also control the GC).









Qwertie said...

Btw, as the author of this C++-vs-C# benchmark...

http://www.codeproject.com/Articles/212856/Head-to-head-benchmark-Csharp-vs-NET

I've learned that optimized C# is sometimes only half as fast as optimized C++ (the Sudoku solver demonstrates). Also, a C++ compiler optimizes more heavily than a C# compiler, which means that performance depends less on hand-optimizing in C++.

Also, the feature set of C++ has improved since I wrote this post - lambdas and compile-time function execution change the balance. But C# has also improved, with async-await and other features. And my LeMP tool enhances C#: http://www.codeproject.com/Articles/995264/Avoid-tedious-coding-with-LeMP-Part

Still, I continue to prefer C# or D or Rust or Swift over C++.

navya said...
This comment has been removed by a blog administrator.