As much as possible, I want to avoid unnecessary code duplication. In my scenario described below, I used Action delegates to avoid code duplication. However, when using the Action delegate approach, the code becomes about 50% -80% slower.
Is there a better performance approach than Action delegates to avoid code duplication in the scenario described below?
I have two methods that are equivalent, except for the innermost long loop operator:
public T[] MethodA<T>(T[] from) { ... for (var i = 0; i < len; ++i) { var j = GetIndex(i); to[j] = from[i]; // This statement differs in MethodA and MethodB } ... return to; } public T[] MethodB<T>(T[] from) { ... for (var i = 0; i < len; ++i) { var j = GetIndex(i); to[i] = from[j]; // This statement differs in MethodA and MethodB } ... return to; }
To avoid code duplication, I applied a helper method that accepts an Action delegate. A delegate call replaces a variable operator, for example:
private T[] HelperMethod<T>(T[], Action<T[], T[], int, int> action) { ... for (var i = 0; i < len; ++i) { var j = GetIndex(i); action(from, to, i, j);
Then I can reduce MethodA and MethodB as follows:
public T[] MethodA<T>(T[] from) { return HelperMethod(from, (src, dest, src_idx, dest_idx) => dest[dest_idx] = src[src_idx]); } public T[] MethodB<T>(T[] from) { return HelperMethod(from, (src, dest, dest_idx, src_idx) => dest[dest_idx] = src[src_idx]); }
Note that the only difference between the reorganized MethodA and MethodB is the order of src_idx and dest_idx in the dest_idx Action call HelperMethod .