using global variables to avoid passing by value
    10 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    min lee
 am 6 Apr. 2024
  
    
    
    
    
    Beantwortet: alelap
      
 am 6 Apr. 2024
            It is often heard that using global variables is a bad practice. 
However, personally, I often declare some variable as global to avoid passing its value to a function call.
My concern is, the function is to be called many many times, and if each time the variable which is a big chuck of data is to be passed by value to the function, it would take a lot of time for copying the data. 
Therefore, is using global variable really a bad idea in this circumstance? 
BTW, the global variable is not changed by the function in my case. 
0 Kommentare
Akzeptierte Antwort
  John D'Errico
      
      
 am 6 Apr. 2024
        
      Bearbeitet: John D'Errico
      
      
 am 6 Apr. 2024
  
      Sorry. I'll call it a bad idea, generated because you erroneously think you are doing something good.
MATLAB does not actually copy the data if it is not changed when you pass it into a function. I know, you don't believe me.
global A
A = rand(20000);
timeit(@() test1(A))
timeit(@() test2)
timeit(@() test3(A))
function y = test1(A)
  y = sum(A); % uses A, but does not change it
end
function y = test2()
  global A % global pass
  y = sum(A); 
end
function y = test3(A)
  A(1,1) = 2; % changing one element of A now forces a copy.
  y = sum(A); 
end
In this example, it seems passing in the array took slightly LESS time than by passing it as global. When I changed one element of A inside the function, now MATLAB was forced to copy the array. So as you can see, passing it in as global gained you nothing.
Skip the globals. They just make your code worse in many ways.
0 Kommentare
Weitere Antworten (1)
  alelap
      
 am 6 Apr. 2024
        I agree with Jonh D'Errico's answer.
MATLAB uses a so called "copy-on-write" mechanism that is exactly designed to tackle such a circumstance:
0 Kommentare
Siehe auch
Kategorien
				Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!