Fastest way to sort an array in descending order

前端 未结 4 1267
春和景丽
春和景丽 2020-12-15 20:51

Why is the following code

Array.Sort(values);
Array.Reverse(values);

much faster at sorting an array in descending order compared to

<
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 21:26

    Because in your second version it has to invoke your (anonymous) function each time it does a compare and then call .CompareTo inside that, so you have two indirections, whereas otherwise it can use build-in comparisons (for primitive types).

    Basically you pay for function call overhead which I bet are eliminated for native primitive types when doing these sorts of operations. Though technically possible (I think), I doubt the Jitter is able to completely inline them in your second case.

提交回复
热议问题