Skip to content

Commit 8971027

Browse files
committed
use native Set when available for tracking deps
1 parent 110798b commit 8971027

File tree

2 files changed

+36
-10
lines changed

2 files changed

+36
-10
lines changed

src/util/env.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,26 @@ export const nextTick = (function () {
104104
timerFunc(nextTickHandler, 0)
105105
}
106106
})()
107+
108+
let _Set
109+
/* istanbul ignore if */
110+
if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) {
111+
// use native Set when available.
112+
_Set = Set
113+
} else {
114+
// a non-standard Set polyfill that only works with primitive keys.
115+
_Set = function () {
116+
this.set = Object.create(null)
117+
}
118+
_Set.prototype.has = function (key) {
119+
return this.set[key] !== undefined
120+
}
121+
_Set.prototype.add = function (key) {
122+
this.set[key] = 1
123+
}
124+
_Set.prototype.clear = function () {
125+
this.set = Object.create(null)
126+
}
127+
}
128+
129+
export { _Set }

src/watcher.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
warn,
88
isArray,
99
isObject,
10-
nextTick
10+
nextTick,
11+
_Set as Set
1112
} from './util/index'
1213

1314
let uid = 0
@@ -47,8 +48,8 @@ export default function Watcher (vm, expOrFn, cb, options) {
4748
this.dirty = this.lazy // for lazy watchers
4849
this.deps = []
4950
this.newDeps = []
50-
this.depIds = Object.create(null)
51-
this.newDepIds = null
51+
this.depIds = new Set()
52+
this.newDepIds = new Set()
5253
this.prevError = null // for async error stacks
5354
// parse expression for getter/setter
5455
if (isFn) {
@@ -163,8 +164,6 @@ Watcher.prototype.set = function (value) {
163164

164165
Watcher.prototype.beforeGet = function () {
165166
Dep.target = this
166-
this.newDepIds = Object.create(null)
167-
this.newDeps.length = 0
168167
}
169168

170169
/**
@@ -175,10 +174,10 @@ Watcher.prototype.beforeGet = function () {
175174

176175
Watcher.prototype.addDep = function (dep) {
177176
var id = dep.id
178-
if (!this.newDepIds[id]) {
179-
this.newDepIds[id] = true
177+
if (!this.newDepIds.has(id)) {
178+
this.newDepIds.add(id)
180179
this.newDeps.push(dep)
181-
if (!this.depIds[id]) {
180+
if (!this.depIds.has(id)) {
182181
dep.addSub(this)
183182
}
184183
}
@@ -193,14 +192,18 @@ Watcher.prototype.afterGet = function () {
193192
var i = this.deps.length
194193
while (i--) {
195194
var dep = this.deps[i]
196-
if (!this.newDepIds[dep.id]) {
195+
if (!this.newDepIds.has(dep.id)) {
197196
dep.removeSub(this)
198197
}
199198
}
199+
var tmp = this.depIds
200200
this.depIds = this.newDepIds
201-
var tmp = this.deps
201+
this.newDepIds = tmp
202+
this.newDepIds.clear()
203+
tmp = this.deps
202204
this.deps = this.newDeps
203205
this.newDeps = tmp
206+
this.newDeps.length = 0
204207
}
205208

206209
/**

0 commit comments

Comments
 (0)