zwlayer
zwlayer

Reputation: 1824

Passing arguments to functions without copying them in JULIA-LANG

let's say I need to create one huge array and use it during my program inside another function. I want to do this without copying this array every time I use it. I know that if I simply give them as argument Julia has a call-by-sharing mechanism and it won't copy the arguments. But if I do something as following, will it still be able to operate without creating copies every time in the loop ?:

function main()
    huge_arr = ones(Float32,20000,30000)
    another_arr = rand(4,5)
    coupled_var = (huge_arr,another_arr)
    for i=1:100  
        target_function(coupled_var)
    end
end

function target_function(x)
   my_first_var = x[1]
   my_second_var = x[2] 
   # some operations here 
end

Upvotes: 4

Views: 1930

Answers (1)

Picaud Vincent
Picaud Vincent

Reputation: 10984

You are manipulating Arrays that are mutable objects (declared as mutable struct Array{...} ...), hence there are passed by reference semantics.

function target_function(x)
   my_first_var = x[1]        # x[1],x[2] are _mutable_ objects 
   my_second_var = x[2]       # -> this only create a new binding (no copy)
   # some operations here 
end

You can check that my_first_var and x[1] are pointing on the same object using pointer_from_objref.

Examples:

function foo(x) 
   y = x
   println("Check ptr $(pointer_from_objref(x) == pointer_from_objref(y)) x:$(pointer_from_objref(x)) y:$(pointer_from_objref(y))")
end

then try:

x=4.5
foo(x)
Check ptr false x:Ptr{Void} @0x00007f25a28a2850 y:Ptr{Void} @0x00007f25a28a2860

-> for a Float64, y=x performs a deep copy

x=rand(5)
foo(x)
Check ptr true x:Ptr{Void} @0x00007f25a284a410 y:Ptr{Void} @0x00007f25a284a410

-> for an array, y=x performs a shallow copy (share same memory address)

Note: in your target_function take care of using component level operations, like my_first_var .*= 2 because something like my_first_var *= 2 creates a new variable.

For instance:

julia> pointer_from_objref(x)
Ptr{Void} @0x00007f25a043f890   <-
                                  |
julia> x *= 2                     |
5-element Array{Float64,1}:
 3.81254
 3.60607
 2.86026
 1.94396
 2.91994                        different memory
                                  |
julia> pointer_from_objref(x)     |
Ptr{Void} @0x00007f25a0afa210  <--|
                                  |
julia> x .*= 2
5-element Array{Float64,1}:
 7.62507
 7.21214
 5.72052
 3.88793
 5.83987                     same memory
                                 |
julia> pointer_from_objref(x)    |
Ptr{Void} @0x00007f25a0afa210 <--|

Upvotes: 12

Related Questions