4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一時オブジェクトの生成コスト回避による高速化

Posted at

正格評価のオブジェクト指向言語で、たとえば大きなベクトルの演算を行う場合に、一時オブジェクトの生成コストがボトルネックになることがある。可読性を保ったまま、そのようなコストを回避して高速化したい。

[C++] Expression Template

Expression Template - Faith and Brave - C++で遊ぼう

型に演算情報を保持しておくことで、要素ごとの遅延評価を実現する。

[Scala] View

Collections - ビュー - Scala Documentation

scala> Seq(1, 2, 3).view.map(_ + 1).map(_ * 2)
res0: scala.collection.SeqView[Int,Seq[_]] = SeqViewMM(...)

scala> res0.force
res1: Seq[Int] = List(4, 6, 8)

toString()の返り値であるSeqViewMM(...)は、mapを二回行うSeqViewという意味。演算そのものを関数として保持しているのがExpression Templateとの違い。この実装の大本はTraversableViewLikeにあって、下記のようになっている。

  override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That = {
    newMapped(f).asInstanceOf[That]
  }
  protected def newMapped[B](f: A => B): Transformed[B] = new { val mapping = f } with AbstractTransformed[B] with Mapped[B]
  trait Mapped[B] extends Transformed[B] {
    protected[this] val mapping: A => B
    def foreach[U](f: B => U) {
      for (x <- self)
        f(mapping(x))
    }
    final override protected[this] def viewIdentifier = "M"
  }
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?