3

In general, if one wants to define local variables and local constants, which of the following is the best programming practice in terms of performance and code "safety"? (Assume Block is not appropriate.)

  1. With inside Module

  2. Module inside With

  3. Define constants along with variables using just Module

Bonus Question

Is the answer the same if Block is appropriate in place of Module?

Just Some Old Man
  • 1,607
  • 1
  • 9
  • 12
  • 3
    I'd say With outermost and Module as inner as possible, even if that means using nested Withs. (Reason: immutable beats mutable.) And avoid Block unless you know why you must use it. But I'll listen to whatever the CS guys have to say. – Alan May 25 '21 at 19:37
  • @Alan When you say “Immutable beats mutable”, you mean performance-wise. Correct? – Just Some Old Man May 26 '21 at 00:56
  • 2
    Related, also you can 'chain' locals with With, e.g. With[{a = 2}, {b=a^2}, {c=b^2}, c] – I.M. May 26 '21 at 06:29
  • 1
    @JustSomeOldMan I think 'immutable beats mutable' is from the point of view of debuggability and reasoning about your program, guaranteeing that immutable variables won't change, confining bug prone mutability to fewer lines of code. The performance differences are small. – flinty May 26 '21 at 13:06

0 Answers0