10

A lot of array boundary checking slows down the speed, this is especially true to 2D arrays. Is there a way to write unsafe code blocks in F#?

1
  • 2
    Not something I do everyday, but F# allows you to write CLR literals in code, I bet there's a way to do unsafe pointer operations through it.
    – Juliet
    Sep 6, 2010 at 15:44

4 Answers 4

9

I'm not a F# programmer but as far as I can see it doesn't seem to have the unsafe keyword.

You could possibly get a performance boost by transforming the 2D array to an one-dimensional array.

Advice 5: Until we get this right, I would suggest that .NET users do what many C++ numerical programmers do: write a class to implement your n-dimensional array. This would be represented as a 1-dimensional array, and the relevant accessors would convert n indices into 1 via appropriate multiplications. We almost certainly wouldn’t eliminate the bounds check into the 1-d array, but at least we’d only do one check!

Array Bounds Check Elimination in the CLR

2
  • The MSDN article you point at makes for a really interesting reading :-) Sep 6, 2010 at 11:48
  • I thought so too and since it's about the CLR it should be language agnostic. Sep 6, 2010 at 14:47
3

See here for some ways to get the compiler to remove boundary checking for you. Basically, you need to write your loops in such a way that the compiler knows your indexes will be in bounds. If it knows it will be in bounds, then when you run in release mode without debugging, the JIT compiler will remove the bounds checks for you.

2

I have not used it to know if/how it applies, but do check out the NativePtr module.

1

Not in this version and I doubt they'll ever add it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.