|
|
global variable are slow?
I coincidently noticed that passing arrays to function is faster than
declaring them global.
Those arryas are not changing inside the function.
ex1.m
---------------------------
function y=a
a=rand(100,100);
......
y=b(a);
end
function y=b(a)
y=2*a;
end
-------------------------------------
ex2.m
---------------------------
function y=a
global a
a=rand(100,100);
......
y=b;
end
function y=b
global a;
y=2*a;
end
-------------------------------------
Am i right?
|
|
0
|
|
|
|
Reply
|
Marios
|
9/17/2010 1:32:06 AM |
|
Marios Karaoulis <marios.karaoulis@gmail.com> wrote in message <73fd6f62-3f63-42d9-aa6c-39ac3e60c2df@v35g2000prn.googlegroups.com>...
> I coincidently noticed that passing arrays to function is faster than
> declaring them global.
So, yet another reason NOT to use them?
Why would you bother doing this test anyway?
John
|
|
0
|
|
|
|
Reply
|
John
|
9/17/2010 1:45:21 AM
|
|
Well I have multiple functions that use the same arrays every time. So
i thought that if I use a struct like this
st.a=..
st.b=...
st.c=...
and declare st as global, I won't have to to type all those arrays in
each function.
|
|
0
|
|
|
|
Reply
|
Marios
|
9/17/2010 1:57:40 AM
|
|
Marios Karaoulis <marios.karaoulis@gmail.com> wrote in message <29e815c4-cbe8-4666-befa-9bceb7ef946d@x18g2000pro.googlegroups.com>...
> Well I have multiple functions that use the same arrays every time. So
> i thought that if I use a struct like this
> st.a=..
> st.b=...
> st.c=...
>
> and declare st as global, I won't have to to type all those arrays in
> each function.
Not a good excuse.
Pass the struct into the function as an argument, and
you won't need to define it more than once. And matlab
does not even make a copy of the struct when you
pass it in.
Or if the functions are nested functions, then since
nested functions share the parent workspace, you
need not do anything special.
You still don't need to use global variables. Global
variables are the lazy solution, and not even a very
good one. Now we know they are slow too.
John
|
|
0
|
|
|
|
Reply
|
John
|
9/17/2010 9:05:11 AM
|
|
The following tech note explains why global may have an impact on MATLAB speed:
"Which type of function call provides better performance in MATLAB? "
http://www.mathworks.com/support/solutions/en/data/1-CMK0MH/?solution=1-CMK0MH
|
|
0
|
|
|
|
Reply
|
Aurelien
|
9/17/2010 9:34:11 AM
|
|
|
4 Replies
260 Views
(page loaded in 0.039 seconds)
|
|
|
|
|
|
|
|
|