Skip to content

Commit

Permalink
Two hot path optimizations (#3513)
Browse files Browse the repository at this point in the history
* Optimize Observable
* Optimize Pass
  • Loading branch information
jridgewell authored Jun 9, 2016
1 parent d4d6731 commit 9e632d8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
14 changes: 7 additions & 7 deletions src/observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ export class Observable {
* @param {function(TYPE)} handler Observer's instance.
*/
remove(handler) {
for (let i = 0; i < this.handlers_.length; i++) {
if (handler == this.handlers_[i]) {
this.handlers_.splice(i, 1);
break;
}
const index = this.handlers_.indexOf(handler);
if (index > -1) {
this.handlers_.splice(index, 1);
}
}

Expand All @@ -64,9 +62,11 @@ export class Observable {
* @param {TYPE} event
*/
fire(event) {
this.handlers_.forEach(handler => {
const handlers = this.handlers_;
for (let i = 0; i < handlers.length; i++) {
const handler = handlers[i];
handler(event);
});
}
}

/**
Expand Down
32 changes: 19 additions & 13 deletions src/pass.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export class Pass {

/** @private {boolean} */
this.running_ = false;

/** @private @const */
this.boundPass_ = () => this.pass_();
}

/**
Expand Down Expand Up @@ -75,31 +78,34 @@ export class Pass {
// execution.
delay = 10;
}

const nextTime = timer.now() + delay;
// Schedule anew if nothing is scheduled currently of if the new time is
// Schedule anew if nothing is scheduled currently or if the new time is
// sooner then previously requested.
if (this.scheduled_ == -1 || nextTime - this.nextTime_ < -10) {
if (this.scheduled_ != -1) {
timer.cancel(this.scheduled_);
}
if (!this.isPending() || nextTime - this.nextTime_ < -10) {
this.cancel();
this.nextTime_ = nextTime;
this.scheduled_ = timer.delay(() => {
this.scheduled_ = -1;
this.nextTime_ = 0;
this.running_ = true;
this.handler_();
this.running_ = false;
}, delay);
this.scheduled_ = timer.delay(this.boundPass_, delay);

return true;
}

return false;
}

pass_() {
this.scheduled_ = -1;
this.nextTime_ = 0;
this.running_ = true;
this.handler_();
this.running_ = false;
}

/**
* Cancels the pending pass if any.
*/
cancel() {
if (this.scheduled_ != -1) {
if (this.isPending()) {
timer.cancel(this.scheduled_);
this.scheduled_ = -1;
}
Expand Down

0 comments on commit 9e632d8

Please sign in to comment.