Search code examples
c#visual-c++c++-cliunmanagedheavy-computation

C# Performance - should I write the computation heavy methods in c++?


I am building a prototype for a quantitative library that does some signal analysis using image processing techniques. I built the initial prototype entirely in C#, but the performance is not as good as expected. Most of the computation is done through heavy matrix calculations, and these are taking up most of the time.

I am wondering if it is worth it to write a C++/CLI interface to unmanaged C++ code. Has anyone ever gone through this? Other suggestions for optimizing C# performance is welcome.


Solution

  • There was a time where it would definitely be better to write in C/C++, but the C# optimizer and JIT is so good now, that for pure math, there's probably no difference.

    The difference comes when you have to deal with memory and possibly arrays. Even so, I'd still work with C# (or F#) and then optimize hotspots. The JIT is really good at optimizing away small, short-lived objects.

    With arrays, you have to worry about C# doing bounds-checks on each access. Read this:

    Link

    Test it yourself -- I've been finding C# to be comparable -- sometimes faster.