Is there a better approach than C # Action delegates to avoid code duplication?

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); // Invoke the Action delegate } ... return to; } 

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 .

+4
source share
1 answer

You can pass a parameter to a method and make A or B depending on the parameter.
I don’t like it, but I'm just saying that it can be done. I really prefer action.

+1
source

Source: https://habr.com/ru/post/1402928/


All Articles