7

Is there any gain in speed, memory usage, whatever, in Swift by defining as much as possible constants x vars?

I mean, defining as much as possible with let instead of var?

radex
  • 6,336
  • 4
  • 30
  • 39
Duck
  • 34,902
  • 47
  • 248
  • 470

1 Answers1

12

In theory, there should be no difference in speed or memory usage - internally, the variables work the same. In practice, letting the compiler know that something is a constant might result in better optimisations.

However the most important reason is that using constants (or immutable objects) helps to prevent programmer errors. It's not by accident that method parameters and iterators are constant by default.

Using immutable objects is also very useful in multithreaded applications because they prevent one type of synchronization problems.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • 1
    "In theory, there should be no difference in speed or memory usage - internally, the variables work the same." This sounds really wrong to me? If you do a 'let a = 5', there won't be any 'instance variable'. It's a constant Int number and no memory needs to be allocated for that. Nor does the CPU need to fetch the value from RAM. It is constant after all and will be significantly faster than a variable. So YES, if something is constant, declare it as such, it'll give you way faster code. Unless most of your program runs in other peoples frameworks - aka Cocoa/UIKit ;-) – hnh Jul 09 '14 at 21:34
  • @hnh That's exactly one of the optimisations I am talking about. Even with `var a = 5` the compiler can decide that it doesn't really need the variable (because it knows how the variable is used) so there doesn't have to be a difference, `let` only enables the compiler to optimize better. – Sulthan Jul 10 '14 at 08:30