What is the difference between copy and deep copy in Julia?
Asked Answered
L

2

8

I am trying to understand the difference between copy() and deepcopy() in Julia. Based on what I read in the Julia docs it seems like deepcopy() copies the values and then makes a while new object un-related to the original object that I copied from. That part makes sense. I am more so confused about the relationship between the following objects:

julia> a = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> b = copy(a)
3-element Array{Int64,1}:
 1
 2
 3

julia> a == b
true

julia> isequal(a,b)
true

Maybe this is just a bad example I chose above but I don't how deep copying would provide a different result (maybe it won't in my simple example but is there a tried and true example that highlights the difference between deep and regular copy?).

Londonderry answered 1/2, 2020 at 13:54 Comment(0)
N
11

The important difference is that deepcopy is recursive while copy isn't:

julia> a = [[1,2,3], [4,5,6]];

julia> b = copy(a);

julia> c = deepcopy(a);

julia> a[1][1] = 11
11

julia> a
2-element Array{Array{Int64,1},1}:
 [11, 2, 3]
 [4, 5, 6]

julia> b
2-element Array{Array{Int64,1},1}:
 [11, 2, 3]
 [4, 5, 6]

julia> c
2-element Array{Array{Int64,1},1}:
 [1, 2, 3]
 [4, 5, 6]
Notable answered 1/2, 2020 at 14:17 Comment(0)
P
5

To complement @pfitzseb answer, note that both == and isequal only check that the corresponding elements of the arrays are equal in some sense, which is still true when copying a to b, even though the two objects are distinct in memory.

The === operator, instead, checks whether two objects are indistinguishable for any program. This operator is sometimes called egality in Julia's jargon:

julia> a = [[1,2,3], [4,5,6]];

julia> b = copy(a);

julia> a == b
true

julia> isequal(a, b)
true

julia> a === b
false
Pollinize answered 1/2, 2020 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.