필터 지우기
필터 지우기

What's the cost of overwriting a variable versus clearing it every time it changes?

조회 수: 19 (최근 30일)
As someone who wants to optimize the performance of his code, I want to know if it is more efficient to clear a variable each time I know it will be overwritten (e.g. a "temp" in a loop, or if the name is reused later) OR if the act of telling Matlab to instantiate a variable of the same name every time I will overwrite actually hurts more than it hurts.
I can't reason whether giving Matlab the "freedom" of choosing memory for each instantiation is good or if it is better to overwrite data to a designation of memory that already exists.
P.S. This would be using the "clear" command if that makes any difference.
Thanks!
  댓글 수: 1
Stephen23
Stephen23 2017년 7월 25일
편집: Stephen23 2017년 7월 25일
Why not simply read the documentation, which states clearly: "Avoid clearing more code than necessary. Do not use clear all programmatically. For more information, see clear."

댓글을 달려면 로그인하십시오.

채택된 답변

per isakson
per isakson 2017년 7월 24일
편집: per isakson 2017년 7월 25일
Comments
and the answer is that clear hurts badly (in the simple case below)
N = 1e6;
tic
val = 17;
for jj = 1 : N
val = jj;
end
toc
tic
for jj = 1 : N
clear val
val = jj;
end
toc
returns
Elapsed time is 0.005792 seconds.
Elapsed time is 17.567347 seconds.
using R2016a (in response to a comment)
  댓글 수: 2
Walter Roberson
Walter Roberson 2017년 7월 24일
The "clear" appears to be less expensive in newer versions relative to whatever release dpb is using, but he is right that it is much more expensive.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Problem-Based Optimization Setup에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by