Nested Functions versus Global Variables

6 ビュー (過去 30 日間)
Catalytic
Catalytic 2019 年 6 月 8 日
コメント済み: Catalytic 2019 年 6 月 10 日
Why are nested functions better for sharing variables between workspaces than global variables? There doesn't seem to be much difference in the way the sharing works. The closest thing to an explanation I've found was the highlighted portion of the Matlab documention below, but I don't know what it means. What does it mean that globals "do not allow names to be reused"? And how then do nested functions allow names to be reused, by contrast?

採用された回答

Stephen23
Stephen23 2019 年 6 月 8 日
編集済み: Stephen23 2019 年 6 月 8 日
"Why are nested functions better for sharing variables between workspaces than global variables?"
Nested functions provide much better control over where those variables can be accessed from. This is huge benefit from a code design perspective, because it makes code easier to understand and debug. They are also more efficient:
"There doesn't seem to be much difference in the way the sharing works"
At first glance they might seem similar, but nested functions are more efficient because MATLAB does not need to search the entire global workspaces to identify that variable, which slows code down: "global variables can decrease performance of your MATLAB code."
"What does it mean that globals "do not allow names to be reused"? And how then do nested functions allow names to be reused, by contrast?"
I find that statement ambiguous, nor do I see a big difference in terms of variable name "re-use". Perhaps some other users can help with this.
  1 件のコメント
Catalytic
Catalytic 2019 年 6 月 10 日
Great. Thank you. I'm starting to think the variable name re-use bit was talking about anonymous functions.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by