0

I want to create an array of references to my arrays. The reason for this is because i want to optimise my fast Fourier transform algorithm to be branchless - or rather, less branchy.

The idea behind it is i have two arrays:

Array1 and Array2

I need to ping pong between the two in a for loop so i want to store the reference to the arrays like this:

[0] = Array1Ref
[1] = Array2Ref
[2] = Array1Ref
. . .

Is it possible to do this in C#? If so how would you define such an array - would i need to use unsafe ?

10
  • Why not just do a swap of the two array variables at the end of the loop? Commented Jul 24, 2020 at 5:40
  • Because that involves using if statements such as if(i%2 == 0) arr1 : arr2 I am trying to see if i can make it faster by aligning the for loop iteration with an array of references. This is a micro optimisation attempt. Commented Jul 24, 2020 at 5:41
  • Are the 2 arrays of the same type? Commented Jul 24, 2020 at 5:41
  • @TheGeneral yes they are same type and length. Commented Jul 24, 2020 at 5:42
  • var someArray = new WhatEverTypeItIs[][]; which is an array of array of WhatEverTypeItIs Commented Jul 24, 2020 at 5:42

1 Answer 1

1

If you just want to access a different array in each iteration of the for loop without using a conditional, you can keep swapping two variables and use one of them.

var arrayRef = Array1;
var theOtherArrayRef = Array2;
for (...) {
    // use arrayRef in places where you would have accessed the array of array references
    
    ...

    // C# 7 tuple syntax
    (arrayRef, theOtherArrayRef) = (theOtherArrayRef, arrayRef);

    // pre-C# 7:
    /*
    var temp = arrayRef;
    arrayRef = theOtherArrayRef;
    theOtherArrayRef = arrayRef;
    */
}
Sign up to request clarification or add additional context in comments.

3 Comments

Does the C#7 tuple compile to the same code or different ?
@WDUK My simple investigation on sharplab.io showed that they compile to different IL, but are JIT'ed to the same ASM code.
@WDUK Wait, no, if I use arrays the IL is the same as well. (I used ints at first).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.