LoginSignup
3
3

More than 5 years have passed since last update.

Closure libraryを使ったJavaScriptの最近流行りのより効果的なプロパティの配置

Last updated at Posted at 2013-10-17

結論

古い書き方

/**
 * @param {number} x
 * @constructor
 */
foo.bar.Hoge = function(x) {
  /** @private */
  this.x_ = x;
}

/**
 * @private {number}
 */
foo.bar.Hoge.prototype.y_;

新しい書き方

/**
 * @param {number} x
 * @constructor
 * @struct
 */
foo.bar.Hoge = function(x) {
  /** @private */
  this.x_ = x;

  /** @private {?number} */
  this.y_ = null;
}

気をつけるべき点は2点.

  • 全てのプロパティをコンストラクタにまとめる.
  • @structをコンストラクタに可能ならばつける.

背景

以前までは,動的に生成されうるプロパティについては,メモリ使用量を減らすため,コンストラクタにはおかれませんでした.Closure libraryにおいては依然型チェックのため,コンストラクタの外に書いていました.これは,型チェックにのみ用いられ,Closure compile後のコードには残りませんでした.

一方で,V8など昨今のJavaScript engineにおいては,より高速なプロパティアクセスのために,lookup tableではなく,hidden classを用いた方法を採用しているため,動的なプロパティの追加はオブジェクトのhidden classのcache missをうみだし,パフォーマンスの低下につながります.つまり, オブジェクトの全てのプロパティをコンストラクタで定義しその後追加を行わない ことが,パフォーマンスの面では効果的と言えます.
これはClosure libraryでは@struct tagにて保証できます.

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3