Benefits with C++ in modern apps

Why would one want to use C++ when developing modern applications for Windows? A lot of developers see C++ as an old, aging, clumsy giant. Why program using C++ when you can be much more productive using a modern high level language like C#? Usually a developer doesn’t have any reason to use C++. A lot of the applications we are writing today are applications that consume data; get some data from a service, make some trivial calculations and display it. Usually nothing that is CPU intensive.

Arithmetics and vectorization

But then there are the benefits. C++ can in some situations bring with it big performance improvements. Especially when it comes to vectorizable arithmetics. Because then the C++ compiler can take advantage of the different kind of SSE instructions available in modern CPUs and make those operations really fast. Such operations can be common when writing photo editing applications.

Memory management

Memory management is another big possible difference. C++ can be written to execute without a garbage collector. A garbage collector [GC] will basically run from time to time and remove all unused objects in your code. This comes with the disadvantage that the GC will use up resources when it runs and that it might run at inappropriate times and some times even not run when you want it to. This ultimately means you have no fine control of the amount of memory allocated.

It is important to keep in mind that managing memory manually does not automatically imply faster running code. Ultimately it is up to you and your skill as a programmer to write fast code. Simply switching your code to run C++ won’t necessarily improve performance.

Lab example

A while ago we had a competence day at the office where we benchmarked some very basic operations using C++ and C# to determine which was faster. We wrote some very simple operations in C# as you can see here:

 

And the same operations using C++ code as you can see here:

 

To make sure we have a fair test, both builds were set to build a release build for x64. I ran each build ten times. Consistently the C++ executable finishes in 175ms with a variation of ±1ms. The C# executable runs almost twice as slow and finishes at 307ms ±10ms.

Mix and match

One thing to keep in mind is that you don’t have to choose one and write your entire application in it. It is possible to write most of your code using C# and then just have a project in C++ that you can delegate compute intensive tasks to.

Further reading

Building a UI: What does it cost?

5 Comments

  1. Ahsan

    why is this so that C++ executes faster than C# ?

  2. Highly descriptive post, I liked that a lot.

Trackbacks for this post

  1. Comprehensive Guide to Learning C++ from Beginning to Proficiency : Invensis Blog

Leave a Reply