Home > Software engineering >  What's the difference between Array.safe and unsafe_get/set
What's the difference between Array.safe and unsafe_get/set

Time:02-02

I asked for some advice to optimize my code on the OCaml forum. I use a lot of Array.set and Array.get (this is most of my code 1 2) and someone told me I could use Array.unsafe_get and Array.unsafe_set to gain some time.

What's the difference between safe and unsafe function in this context ?

CodePudding user response:

The unsafe versions do not perform boundary checks. So if you access an index that is out of the array boundaries you might get a segmentation fault or something worse, where the safe version will just throw an exception.

The unsafe functions should only be used1 if you already checked the boundaries, explicitly or implicitly (e.g., checked them in the loop condition), e.g.,2

(* here [i] is guaranteed to be in range by the loop condition,
   so we can use the unsafe version to remove double check  *)
let unsafe_init_array xs v =
  for i = 0 to Array.length xs - 1 do
    Array.unsafe_set xs i v
  done

1)As a side note, I personally never saw any significant, if any at all, performance boost from using these functions. My guess is that in modern superscalar computers speculative execution is able to load data and perform the boundary check in parallel. So, in the end, they are not worth the risk. It could be different on less complex architectures though. And as usual, YMMV, so take this note with a grain of salt.

2) The safe version of this loop is only 6% slower on my machine, but is safer and easier to read,

let safe_init_array xs v =
  for i = 0 to Array.length xs - 1 do
    xs.(i) <- v
  done

CodePudding user response:

Array.get and Array.set checks that the index is within the bounds of the array. For instance,

[||].(2) 0

fails with

Exception: Invalid_argument "index out of bounds".

The unsafe versions do not perform this test and thus

(Array.unsafe_get [||] 2) 0

fails with a segmentation fault.

In hot loop, the bound checking test might slow the loop.

  •  Tags:  
  • Related