# Safe Usage of UnsafeArrays

**URL:** <https://discourse.julialang.org/t/safe-usage-of-unsafearrays/79285>\
**Category:** General Usage\
**Tags:** memory-allocation\
**Created:** [April 10, 2022, 4:55am UTC](https://discourse.julialang.org/t/safe-usage-of-unsafearrays/79285 "2022-04-10T04:55:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cortner](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cortner/32/204_2.png) [@cortner](https://discourse.julialang.org/u/cortner)\
**Post date:** [April 10, 2022, 4:55am UTC](https://discourse.julialang.org/t/safe-usage-of-unsafearrays/79285/1 "2022-04-10T04:55:20Z")

</div>

Is the following a “safe” usage of `UnsafeArrays?

```julia
struct SafeUnsafeArray{T, N} <: AbstractArray{T, N}
   A::UnsafeArray{T, N}
   _A::Vector{UInt8}
end

x = zeros(UInt8, 800)
ptr = Base.unsafe_convert(Ptr{Float64}, x)
u = UnsafeArray(ptr, (100,))
s = SafeUnsafeArray(u, x)

```

Now, may I pass `s` around some functions until I no longer need it, rather than use it only “locally” as suggested by the `UnsafeArrays` documentation?

NOTE: I’m fully aware of `reinterpret`, but it seems in some of my use-cases, `UnsafeArrays` is anywhere from 0 to 30% faster.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [April 11, 2022, 2:01pm UTC](https://discourse.julialang.org/t/safe-usage-of-unsafearrays/79285/2 "2022-04-11T14:01:08Z")

</div>

> [@cortner](#):
>
> but it seems in some of my use-cases

what’s the benchmark?

---

<div class="post-metadata">

**Author:** ![cortner](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cortner/32/204_2.png) [@cortner](https://discourse.julialang.org/u/cortner)\
**Post date:** [April 11, 2022, 3:13pm UTC](https://discourse.julialang.org/t/safe-usage-of-unsafearrays/79285/3 "2022-04-11T15:13:28Z")

</div>

Assemble a feature vector - anywhere between length 10 to 100000 - return it to the caller then the caller releases the array back into a pool. Similar tasks with forward and backward derivatives.

So basically I only use getindex and setindex

I find that in MWEs avoiding the allocation doesn’t help that much but when embedded in bigger tasks it can give 10-30% speed up. Not game changing but nice to have
