Why is .NET faster than C++ in this case?

后端 未结 13 1471
长发绾君心
长发绾君心 2021-02-02 00:59

Make sure you run outside of the IDE. That is key.

-edit- I LOVE SLaks comment. \"The amount of misinformation in these answers is staggering.\" :D

13条回答
  •  情歌与酒
    2021-02-02 01:18

    One important thing to remember when comparing languages is that if you do a simple line-by-line translation, you're not comparing apples to apples.

    What makes sense in one language may have horrible side effects in another. To really compare the performance characteristics you need a C# version and a C++, and the code for those versions may be very different. For example, in C# I wouldn't even use the same function signature. I'd go with something more like this:

    IEnumerable Fibonacci()
    {
       int n1 = 0;
       int n2 = 1;
    
       yield return 1;
       while (true)
       {
          int n = n1 + n2;
          n1 = n2;
          n2 = n;
          yield return n;
       }
    }
    

    and then wrap that like this:

    public static int fib(int n)
    {
        return Fibonacci().Skip(n).First();
    }
    

    That will do much better, because it works from the bottom up to take advantage of the calculations in the last term to help build the next one, rather than two separate sets of recursive calls.

    And if you really want screaming performance in C++ you can use meta-programming to make the compiler pre-compute your results like this:

    template struct fibonacci
    {
        static const int value = fibonacci::value + fibonacci::value;
    };
    
    template<> struct fibonacci<1>
    {
        static const int value = 1;
    };
    
    template<> struct fibonacci<0>
    {
        static const int value = 0;
    };
    

提交回复
热议问题