Skip to content

Instantly share code, notes, and snippets.

@oleg-koval
Last active January 29, 2019 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleg-koval/7946785889874861be89dab3ae62d85b to your computer and use it in GitHub Desktop.
Save oleg-koval/7946785889874861be89dab3ae62d85b to your computer and use it in GitHub Desktop.
Shortly about immutability vs mutability

Consolidated this info from various Stack Overflow questions:

Mutable data

  • you need to know:
    • what data means
    • where data was first assigned
    • where data can be changed
    • when data can be changed
    • if those changes can happen concurrently and require locks, what sequence locks need to be acquired in
    • if changing the data needs coordination with others
    • if data is actually changed here
  • complexity: mutable data is inherently complex, because it can change

Immutable data

  • you need to know:
    • what data means
    • where it was first assigned
    • (perhaps) how it is used here
  • garbage collection efficiency
  • lock-free operation
  • efficient substructure sharing
  • safely access data from 2 threads without worrying about locks or other concurrency issues
  • produces code that's easier to reason about, easier to test, and easier to be confident about its correctness
@santiago-su
Copy link

santiago-su commented Jan 29, 2019

could do

//splice   MUTABLE
const array = [1,2,3,4,5];
array.splice(2);   // -> [3,4,5]

//slice   IMMUTABLE
const array2 = [1,2,3,4,5];
array2.slice(2);   // ->   [3,4,5]

console.log(array);   //  -> [1,2]    Splice mutates original array
console.log(array2);  //  -> [1,2,3,4,5]  Slice doesn't mutate anything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment