I wanted to make an object where you could not directly mutate the variables so I decided to create what is essentially a store with a reducer similar to redux. When I return the store with the get()
function I am returning a copy of the store instead of the original store so it cannot be mutated directly. There are variables in the store that I want to remain untouched throughout the controller.
My question is are there any serious performance tradeoffs that I should be aware of when making a copy of the object vs returning the entire object. The get()
function will be used a lot so many copies will be made. I also use it in a requestAnimationFrame
function where the get()
function will be called a lot back to back for each animationFrame
. I assume that the old copy will be removed from memory when no longer in use but I am not for sure.
Here is a very simple example.
const reducer = (store, action) => {
switch(action.type) {
case 'SET_FOO':
return {
...store,
foo: action.payload
}
case 'SET_BAR':
return {
...store,
bar: action.payload
}
default:
return store
}
}
const createController = () => {
let store = {
foo: 'foo',
bar: 'bar'
}
const get = () => ({...store})
const dispatch = (action) => (store = reducer(store, action))
// A bunch of other irrelevant functions here
return {
get,
dispatch
}
}
As you can see in the get()
function I am sending a copy of the store back instead of the actual store. This way it is impossible for the person creating the controller to mutate the store directly. If I just returned the store you could do something like the following and directly mutate the store which I am trying to avoid.
const ctl = createController()
const store = ctl.get()
store.foo = 'baz'
console.log(store.get().foo)
// result would be 'baz'
But if you send back a copy of the store then they could not directly mutate the store but instead you would have to dispatch to the reducer to mutate it. But are there any serious performance concerns that I should take in consideration here. I know adding more objects can use more memory but I don't think it would make a huge difference.
Any insights would be appreciated. Thanks