I have the following code in Julia:
using LightGraphs
using LinearAlgebra
prop=[1 rand() rand() rand() rand(); rand() 1 rand() rand() rand(); rand() rand() 1 rand() rand(); rand() rand() rand() 1 rand(); rand() rand() rand() rand() 1]
prop=Symmetric(prop)
thresh=sort(unique(prop)
g=[SimpleGraph(0) for a in 1:length(thresh)]
for j=1:length(thresh)
g[j]=Graph(Int.(prop.>=thresh[j])-I)
end
I need to create a copy of g
, say g2
, on which I need to use the function add_edge!
but without modifying the original object g
. I know that g2=deepcopy(g)
will do perfectly the trick, but if g
is very large (it's not the case in this simple example), the function deepcopy()
takes a large amount of time to create the independent copy. I measured it with @time
. Isn't there an alternative way in Julia to do what I want without taking a large amount of time for just making the copy of g
? I have to run the code several times and want avoid to consume time just for copying g
.
I don't think you want an alternative to deepcopy
, which is already doing what you want. It's just that heap memory allocation (as done by deepcopy) takes time.
What you can do is make a single copy of g
, then update that every time you'd need the deepcopy
function, it might look like this
g_copy = deepcopy(g)
add_edge!(g_copy[i], edge)
# ... do stuff
g_copy .= g
In that way you'll just change the contents of g_copy
but never release the memory, so should be faster. I should mention this is untested (as I can't naturally expand your MWE, which doesn't use deepcopy
or add_edge!
at all).