If you want to put dimensions in the type domain, you can use SizedArray
or SizedVector
:
julia> using StaticArrays
julia> x::SizedVector{100, Float64, Vector{Float64}} = zeros(100);
julia> x = rand(50)
ERROR: DimensionMismatch: expected input array of length 100, got length 50
Stacktrace:
[1] dimension_mismatch_fail(::Type{SizedVector{100, Float64, Vector{Float64}}}, a::Vector{Float64})
@ StaticArrays ~/.julia/packages/StaticArrays/85pEu/src/convert.jl:196
[2] convert(::Type{SizedVector{100, Float64, Vector{Float64}}}, a::Vector{Float64})
@ StaticArrays ~/.julia/packages/StaticArrays/85pEu/src/convert.jl:201
[3] top-level scope
@ REPL[18]:1
julia> x = rand(100)
100-element Vector{Float64}:
0.20602787252356625
0.5326407584784596
0.6315752664438412
...
Regarding allocations, you probably want functions that end with a !
to reuse memory that you have already allocated.
julia> using Random
julia> rand!(x)
100-element SizedVector{100, Float64, Vector{Float64}} with indices SOneTo(100):
0.6011787356901267
0.7390623881486247
0.9652497761882068
...
In the context of Julia, it is quite hard to leak memory. The garbage collector is keeping track of memory allocations and can still reclaim them. To leak memory, you would need to manually allocate memory via Libc.malloc
or calling out to C or Fortran.
Perhaps what you mean is if you are needlessly allocating memory?
As the @time
and @allocated
macros show, the calls to rand
allocate new memory.
julia> @time x = rand(100);
0.000008 seconds (3 allocations: 1.766 KiB)
julia> @allocated x = rand(100)
1808
Rather if you want to reuse already allocated memory use rand!
as I suggested above.
julia> @time rand!(x);
0.000005 seconds
julia> @allocated rand!(x)
0
Also comapare the following approaches to zeroing out memory.
julia> @time x = zeros(100);
0.000007 seconds (3 allocations: 1.766 KiB)
julia> @time x .= 0;
0.000004 seconds
julia> @time fill!(x, 0);
0.000004 seconds