which one is faster? defining a variable as a global variable or as an input of function?

14 ビュー (過去 30 日間)
I want to know which one is faster? defining a variable as a global variable or as an input of function?

採用された回答

Walter Roberson
Walter Roberson 2015 年 8 月 24 日
global is slower. The location of the global variable must be searched at execution time when the "global" is encountered. The location of passed parameters is already known.
  1 件のコメント
Diaa
Diaa 2021 年 6 月 24 日
編集済み: Diaa 2021 年 6 月 24 日
Is it faster to define auxiliary variables instead of retrieving values from a parent matrix?
In other words, which one is faster:
a = randn(3,4);
clear b c d g
tic
b = a(3,4);
c = 5*b; d = 10*b; g = 20*b;
toc
clear c d g
tic
c = 5*a(3,4); d = 10*a(3,4); g = 20*a(3,4);
toc
knowing that my R2021a version tells me the second way is faster despite indexing into variable a multiple times?

サインインしてコメントする。

その他の回答 (1 件)

David Young
David Young 2015 年 8 月 23 日
編集済み: David Young 2015 年 8 月 23 日
It is usually a bad idea to use global variables. There are many papers, going back over 40 years or more, explaining why. One example is this chapter. I strongly recommend you avoid them. (Global variables, that is, not the papers.)
It is very unlikely that using a global rather than passing an argument will make a noticeable difference to your execution time. If you really suspect it might, the best way to find out is to do some tests using timeit.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by