Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB performance benefit from clearing temporary variables?

MATLAB has an annoying feature of sometimes requiring you to create temporary variables, e.g. temporary_variable, in order to create something to be used in another variable, after which the temporary variable is not used anywhere else in the code. Is there a performance benefit to using clear temporary_variable after the temporary variable has done its job? What the most performance efficient way of handling this kind of situation? Thanks for your insight!

like image 351
space_voyager Avatar asked Nov 24 '15 15:11

space_voyager


1 Answers

Several comments:

  1. Unless you're running out of memory, clearing variables almost certainly won't help performance.
  2. In my experience, the problem with a proliferation of temporary variables is its contribution to programming mistakes. Eg. you have a typo, writing x instead of X but your code doesn't immediately throw an error because you defined an x previously.
  3. That said, I almost never bother to clear temporary variables during a MATLAB script.

Tips to keep workspace clean (mostly to help reduce coding errors)

  1. Use the clear command at the start of a script. (This reduces Heisenbug problems where code works or doesn't work depending on what you did before running the script...)
  2. Put much/most of your code in user defined functions. Variables local to a function automatically go out of scope (i.e. disappear) once the function ends, and within a function, you can't mistakenly access variables in your workspace that you shouldn't be accessing.
like image 92
Matthew Gunn Avatar answered Nov 15 '22 06:11

Matthew Gunn