Is it possible to call a call to common programs and writing algorithms in C #, and to avoid the overhead of a dynamic solution?
Consider a simple example:
static void QuickSort<T>(T[] arr, int left, int right, Comparison<T> compare) { do { int i = left; int j = right; var x = arr[i + ((j - i) >> 1)]; do { while (i < arr.Length && compare(x, arr[i]) > 0) i++; while (j >= 0 && compare(x, arr[j]) < 0) j--; if (i > j) { break; } if (i < j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } i++; j--; } while (i <= j); if (j - left <= right - i) { if (left < j) QuickSort(arr, left, j, compare); left = i; } else { if (i < right) QuickSort(arr, i, right, compare); right = j; } } while (left < right); }
What could you name:
QuickSort(buffer, 0, buffer.Length - 1, (a, b) => a.CompareTo(b))
Despite its apparent effectiveness, this benign example performs an indirect (i.e. virtual) call for each comparison.
Obviously, the processor cannot optimize indirect calls, and therefore they work poorly. On my computer, this means a 25% reduction in performance - from about 3,600 pips / ms to 2,700 units / ms.
Is there a way to avoid such indirect calls when writing generic code?
Regardless of how much I deal with delegates, DynamicMethod
and the like, there always seems to be an indirect call between library code and user code, which clearly negatively affects performance.