Skip to content

Commit

Permalink
Delay copying listeners until is necessary
Browse files Browse the repository at this point in the history
We can avoid excessive slice() calls by only copying the listeners if they are modified during dispatch()
  • Loading branch information
gaearon committed Jan 31, 2016
1 parent 24aade4 commit c031c0a
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,16 @@ export default function createStore(reducer, initialState, enhancer) {

var currentReducer = reducer
var currentState = initialState
var listeners = []
var currentListeners = []
var nextListeners = currentListeners
var isDispatching = false

function beforeMutatingListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice()
}
}

/**
* Reads the state tree managed by the store.
*
Expand Down Expand Up @@ -95,17 +102,21 @@ export default function createStore(reducer, initialState, enhancer) {
throw new Error('Expected listener to be a function.')
}

listeners.push(listener)
var isSubscribed = true

beforeMutatingListeners()
nextListeners.push(listener)

return function unsubscribe() {
if (!isSubscribed) {
return
}

isSubscribed = false
var index = listeners.indexOf(listener)
listeners.splice(index, 1)

beforeMutatingListeners()
var index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
}
}

Expand Down Expand Up @@ -160,9 +171,9 @@ export default function createStore(reducer, initialState, enhancer) {
isDispatching = false
}

var currentListeners = listeners.slice()
for (var i = 0; i < currentListeners.length; i++) {
currentListeners[i]()
var listeners = currentListeners = nextListeners
for (var i = 0; i < listeners.length; i++) {
listeners[i]()
}

return action
Expand Down

0 comments on commit c031c0a

Please sign in to comment.