CRquantum
CRquantum

Reputation: 626

How to prevent global variable or array in module?

I am coming from Fortran to Julia. I know in Julia want to prevent using global variables. But the thing is, how to prevent using global variables in a module?

For example, in the following module,

module Mod
global AAA=zeros(1000000000)

function f(x)
change the most up to date AAA with x in some way.
return nothing
end

function g(x)
using the most up to date AAA, then change/update AAA with x in some way.
return nothing
end

end

In the above example, I need to update the very big array AAA, so I put AAA in the global. So f(x) and g(x) can use the most updated AAA and further update them.

Now since Julia discourage the use of global variable, so in my case, what do I do?

I mean, do I put AAA just in the argument of f(x) and g(x) such that they become f(x,AAA) and g(x,AAA)?

Is passing a very big array like AAA in the argument really faster than putting AAA just as a global variable?

Upvotes: 2

Views: 208

Answers (1)

call me Steve
call me Steve

Reputation: 1727

It is possible to pass the array in question to the functions. Here is an updated version of your pseudo code.

module Mod
AAA=zeros(1000000000)

function f!(ba, x) # the ! mark to indicate that ba will be  updated 
    ba[1]=x
    return nothing
end

function g!(ba, x)
    ba[1] +=x
    return nothing
end

function example()
    f!(AAA,1)
    g!(AAA,2)
    @show(AAA[1])
end


end

I can't currently benchmark this, but you could do it if you want to convince yourself there is no penalty in passing the array as an argument.

It is common practice to add a ! when the function mutates the content of the argument. Also, the arguments changed are put first in the list. Of course, these are only conventions, but it makes it easier for others to understand the intent of your code.

Upvotes: 1

Related Questions