Processing math: 100%

2015年7月27日月曜日

[SDN]List性能問題

懸案だったMonadic Programming、Functional Reactive Programmingもある程度目処がついてきたこともあり、要件定義で作成されたモデルを実装に落とし込むという流れの中での総合的なScalaプログラミングの方法論をScala Design Noteという切り口で考察していこうと思います。

大昔にJava World誌で「Java Design Note」という連載を書いていましたが、そのScala版をイメージしています。

問題

Scalaを実務に使う場合に注意が必要なのがListの性能問題です。

Scalaでは関数型言語の伝統を踏襲してLispのList由来のListを基本データ構造としています。システムの各種デフォルトもListを使う方向になっていますし、文法を説明する場合にもListを使用するケースが多いと思います。

Listは関数型プログラミングとの相性はとてもよいので妥当な選択ではあるのですが、要素の後方追加が致命的に遅いという問題を持っています。この問題があるためListの使い方には注意が必要です。

致命的に遅いといっても小さなプログラムではほぼ問題はありませんが、プログラムの処理が本格化し、扱うデータ規模が大きくなってくると顕在化してきます。

ListはScalaの基本データ構造であり、普通にScalaを使っていると色々な所でListが自然に使用されますが、これがプロダクションコードとしてはアンチパターンという点がScalaプログラミングのハマりどころとなっています。

きっかけ

前回「Scalaへの道」で以下のcase class Wordsを実装しました。

この実装を行う中で、このように復数のオブジェクトを保持しているcase classを足し込んでいくような処理におけるListの危険性が判明したのが、今回の記事のきっかけになっています。

  1. package sample  
  2.   
  3. case class Words(  
  4.   smalls: Vector[String],  
  5.   middles: Vector[String],  
  6.   larges: Vector[String]  
  7. ) {  
  8.   def +(word: String): Words = {  
  9.     if (word.length <= 3)  
  10.       copy(smalls = smalls :+ word)  
  11.     else if (word.length > 7)  
  12.       copy(larges = larges :+ word)  
  13.     else  
  14.       copy(middles = middles :+ word)  
  15.   }  
  16.   
  17.   def +(words: Words): Words = {  
  18.     copy(  
  19.       smalls ++ words.smalls,  
  20.       middles ++ words.middles,  
  21.       larges ++ words.larges  
  22.     )  
  23.   }  
  24.   
  25.   def ++(words: Seq[String]): Words = {  
  26.     words.foldLeft(this)(_ + _)  
  27.   }  
  28.   
  29.   override def toString() = s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  30. }  
  31.   
  32. object Words {  
  33.   val empty = Words(Vector.empty, Vector.empty, Vector.empty)  
  34.   
  35.   def apply(word: String): Words = empty + word  
  36.   
  37.   def apply(words: Seq[String]): Words = empty ++ words  
  38.   
  39.   def getTokens(s: String): Vector[String] =  
  40.     s.split(" ").filter(_.nonEmpty).toVector  
  41. }  
問題

性能測定のため前述のcase class Wordsを単純化し、測定パターンごとに復数の実装を用意しました。以下は、宣言にIndexedSeq、実装にVectorを採用した実装であるWordsIVです。これを含めて16パターンの測定を行いました。(後述の表参照)

  1. case class WordsIV(  
  2.     smalls: IndexedSeq[String],  
  3.     middles: IndexedSeq[String],  
  4.     larges: IndexedSeq[String]  
  5.   ) {  
  6.     def +(word: String): WordsIV = {  
  7.       if (word.length <= 3)  
  8.         copy(smalls = smalls :+ word)  
  9.       else if (word.length > 7)  
  10.         copy(larges = larges :+ word)  
  11.       else  
  12.         copy(middles = middles :+ word)  
  13.     }  
  14.   
  15.     override def toString() = {  
  16.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  17.     }  
  18.   }  
  19.   
  20.   object WordsIV {  
  21.     val empty = WordsIV(Vector.empty, Vector.empty, Vector.empty)  
  22.   }  

case class WordsVは以下のようにして積算した時の実行時間を計測しました。

  1. go("WordsIV") {  
  2.       inputs.foldLeft(WordsIV.empty)(_ + _)  
  3.     }  
測定のパターン

性能測定パターンは以下になります。この中の「WordsIV」のプログラムは前述しました。その他のパターンのプログラムは一番最後に一括で置いておきます。

測定名性能(ms)宣言実装追加場所備考
WordsJ30ArrayBufferArrayBuffer
WordsV33VectorVector
WordsL27717ListList
WordsVP32VectorVector
WordsLP28ListList
WordsSV19840SeqVector
WordsSVV32SeqVectorロジック工夫
WordsS27620SeqSeq
WordsSP31SeqSeq
WordsIV30IndexedSeqVector
WordsIA614IndexedSeqArray
WordsI29IndexedSeqIndexedSeq
WordsIP29IndexedSeqIndexedSeq
WordsBuilderV25VectorArrayBufferBuilder
WordsBuilderL29ListArrayBufferBuilder
WordsBuilderS25SeqArrayBufferBuilder

考察

性能測定の結果をまとめると以下のような結果が得られました。

  • Listに追記する処理は圧倒的に遅い (WordsL, WordsSV, WordsS)
  • ArrayBuffer、Vectorへの追記、List、Vectorへの前置挿入はほとんど同じ性能 (WordsJ, WordsV, WordsVP, WordsLP)
  • SeqとVectorの組合せはロジックを工夫しないと非常に遅くなることがある (WordsSV)
  • Vectorへの前置挿入はほとんどListと変わらない (WordsVP, WordsLP)

Seqのデフォルト実装はListなのでWordsSも事実上Listの追記処理のパターンになります。WordLとWordsSの結果からListの追記処理が非常に低速なのは明らかです。

また、宣言にSeq、初期実装にVectorを使うWordsSVは実装にVectorを使う意図なのですが、ロジックの綾で実際はListが使われるようになるらしく非常に低速です。

ただWordsSVと同じパターンのWordsSVVは宣言Vector、実装VectorのWordsVなどと同じ性能が出ています。宣言にSeq、初期実装にVectorのパターンは実装時のロジックの綾で非常に低速になったり、通常性能になったりしてリスクが高い処理パターンといえます。

コンテナの選択

まずコンテナの候補としてはVector一択かなと考えています。

Listは追記性能が非常に遅いので、使い方に注意が必要な点がデメリットです。また、単方向リストによる実装方式からメモリも多目に消費することが推測されます。

VectorとListの性質を比較した場合、Listは前置挿入が得意で追記が苦手、Vectorは追記が得意で前置挿入が苦手、という整理の仕方がありますが、Vectorは追記が得意で前置挿入も大丈夫、というの実際のところです。

Vectorは万能で用途を選ばないのに対して、Listは追記が苦手という弱点があるので、利用局面に応じて意識して使用する必要があります。

このためコンテナの選択は弱点がないVectorの一択と考えてよいと思います。

Listは関数型言語の伝統的なデータ構造なので変な話ですが、ScalaにおけるListはHashSetなどと同様の特殊用途向けコンテナとして割り切って使うぐらいがベストプラクティスではないかと思います。

Listの長所

Listが向いている「特殊用途」は何かという話ですが、伝統的な関数型プログラムということになります。

関数型プログラミングでよく出てくる再帰呼び出しでの利用は、専用の文法が用意されていて便利です。たとえば、以下のようなコーディングパターンです。

  1. def f(a: List[Int]): Int = {  
  2.   a match {  
  3.     case Nil => 0  
  4.     case x :: xs => x + f(xs)  
  5.   }  
  6. }  

ただVectorを始めとするSeqでも以下のように書けるので使えないと困るという程ではありません。

  1. def f(a: Vector[Int]): Int = {  
  2.   a.headOption match {  
  3.     case None => 0  
  4.     case Some(x) => x + f(a.tail)  
  5.   }  
  6. }  
補足:末尾再帰呼び出し

念のために補足です。

「Listの長所」で取り上げたコードはList処理を分かりやすく提示するのが目的なので再帰呼び出しは自然な方法を用いていますが、実はこの「自然な方法」はプロダクションコードとしては適切ではありません。というのは、このコードでは末尾再帰の最適化が得られないのでスタックオーバーフローのリスクがあるためです。

今回の場合は実務的には以下のようなコーディングになります。

  1. def f(a: List[Int]): Int = {  
  2.   @annotation.tailrec  
  3.   def go(b: List[Int], sum: Int): Int = {  
  4.     b match {  
  5.       case Nil => sum  
  6.       case x :: xs => go(xs, x + sum)  
  7.     }  
  8.   }  
  9.   go(a, 0)  
  10. }  
  1. def f(a: Vector[Int]): Int = {  
  2.   @annotation.tailrec  
  3.   def go(b: Vector[Int], sum: Int): Int = {  
  4.     b.headOption match {  
  5.       case None => sum  
  6.       case Some(x) => go(b.tail, x + sum)  
  7.     }  
  8.   }  
  9.   go(a, 0)  
  10. }  

宣言の選択

オブジェクトの集まりを実現する場合に使用するコンテナとして概ね以下の4つを日常的に使用します。

コンテナ種別説明
Seqトレイト先頭からのシーケンシャルアクセス
IndexedSeqトレイトランダムアクセスに適したシーケンス
List具象クラスList構造のSeq
Vector具象クラス配列をベースとしたIndexedSq

SeqとIndexSeqはトレイトなので、それぞれ復数の具象クラスに対応します。関数の引数やオブジェクトのインスタンス変数にSeqやIndexSeqを指定することで、プログラムの実行時に具象クラスを使い分ける事ができるようになります。

ListとVectorは具象クラスなので、引数やインスタンス変数の型として指定すると型を最終決定してしまうことになります。逆に明確な決定が行われるので、予想外の動きによる性能劣化という事態は避ける事ができます。

一般的には、できるだけ抽象度の高いものを選択するのが得策です。その一方で、Seqを使うと前述のListの性能問題が発生する可能性があるので、一定のリスクがあります。

つまり汎用性と性能リスクのバランスを勘案して実装戦略を考えることになります。

実装戦略

case classの属性としてオブジェクトの集まりが必要になった時の実装戦略です。

以下が論点になります。

  • case class内での宣言
  • 実装に使用するコンテナの選択

まず実装に使用するコンテナの選択は前述した通りVector一択としました。

Listは追記性能が非常に遅いので、使い方に注意が必要な点がデメリットです。また、単方向リストによる実装方式からメモリも多目に消費することが推測されます。

つまり、実装の選択はVectorのみなので、残る選択は宣言に何を使うのかになります。

シンプル戦略

アプリケーション内で閉じた範囲で使用するcase classであれば、あまり凝ったつくりにしてもメリットは少ないので、宣言と実装の両方にVectorを使うのが簡明です。

性能測定パターンではWordsVが対応します。

安全戦略

宣言にSeqまたはIndexedSeq、実装にVectorを使うのが本格的な戦略です。

用途に応じてSeqとIndexedSeqを使い分けることができれば理想的ですが、Seqは前述のList性能問題が発生する可能性が出てくるので、安全策を採るのであれば常にIndexedSeqを使う戦略が有効です。

性能測定パターンではWordsIVが対応します。

上級戦略

対象となるcase classを操作する時のアクセスパターンが先頭からのシーケンシャルアクセスのみである場合、宣言には一番汎用性の高いSeqを使うのが理想的です。

性能測定パターンではWordsSVVが対応します。

Seqを使うことで、以下のように他のSeqコンテナをそのまま設定することとができるようになります。

  1. WordsSVV(List("a"), List("abcde"), List("abcdefghijk"))  

設定されたListをアクセスする場合は、そのままListでよいですが、後方追加の積算をそのままListで行うと性能問題が出てきます。

そこで、前出の「SeqとVectorの組合せはロジックを工夫」が必要になってきます。

具体的にはWordsSVで使用している以下のロジックでは不適切です。

  1. def +(word: String): WordsSV = {  
  2.       if (word.length <= 3)  
  3.         copy(smalls = smalls :+ word)  
  4.       else if (word.length > 7)  
  5.         copy(larges = larges :+ word)  
  6.       else  
  7.         copy(middles = middles :+ word)  
  8.     }  

WordsSVVで使用している以下のロジックにする必要があります。このロジックのポイントは後方追加の演算の前にSeqをVectorに変換しているところです。こうすることによって、以降の計算に使用されるコンテナはVectorになるのでList性能問題は発生しなくなります。

  1. def +(word: String): WordsSVV = {  
  2.       if (word.length <= 3)  
  3.         copy(smalls = smalls.toVector :+ word)  
  4.       else if (word.length > 7)  
  5.         copy(larges = larges.toVector :+ word)  
  6.       else  
  7.         copy(middles = middles.toVector :+ word)  
  8.     }  

まとめ

case classを漫然と作っているとListの性能問題に遭遇してしまう可能性があるので、実装戦略としてまとめてみました。

結論としては以下の3パターンを適材適所で選んでいくのがよさそうです。

  • シンプル戦略 : 宣言 => Vector、実装 => Vector
  • 安全戦略 : 宣言 => IndexedSeq、実装 => Vector
  • 上級戦略 : 宣言 => Seq、実装 => Vector

上級戦略は「SeqとVectorの組合せはロジックを工夫」を意識しておく必要があるのが難点です。このような考慮が負担になるような場合は、安全戦略を基本戦略にしておくのが簡明でよいと思います。

測定プログラム

  1. package sample  
  2.   
  3. import scala.util.Try  
  4. import scala.collection.mutable.ArrayBuffer  
  5. import scalaz._, Scalaz._  
  6. import scalaz.stream._  
  7. import scalaz.concurrent.Task  
  8.   
  9. object Performance {  
  10.   class WordsJ(  
  11.     val smalls: ArrayBuffer[String] = new ArrayBuffer[String],  
  12.     val middles: ArrayBuffer[String] = new ArrayBuffer[String],  
  13.     val larges: ArrayBuffer[String] = new ArrayBuffer[String]  
  14.   ) {  
  15.     def +(word: String): WordsJ = {  
  16.       if (word.length <= 3)  
  17.         smalls += word  
  18.       else if (word.length > 7)  
  19.         larges += word  
  20.       else  
  21.         middles += word  
  22.       this  
  23.     }  
  24.   
  25.     override def toString() = {  
  26.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  27.     }  
  28.   }  
  29.   
  30.   case class WordsV(  
  31.     smalls: Vector[String],  
  32.     middles: Vector[String],  
  33.     larges: Vector[String]  
  34.   ) {  
  35.     def +(word: String): WordsV = {  
  36.       if (word.length <= 3)  
  37.         copy(smalls = smalls :+ word)  
  38.       else if (word.length > 7)  
  39.         copy(larges = larges :+ word)  
  40.       else  
  41.         copy(middles = middles :+ word)  
  42.     }  
  43.   
  44.     override def toString() = {  
  45.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  46.     }  
  47.   }  
  48.   
  49.   object WordsV {  
  50.     val empty = WordsV(Vector.empty, Vector.empty, Vector.empty)  
  51.   }  
  52.   
  53.   case class WordsL(  
  54.     smalls: List[String],  
  55.     middles: List[String],  
  56.     larges: List[String]  
  57.   ) {  
  58.     def +(word: String): WordsL = {  
  59.       if (word.length <= 3)  
  60.         copy(smalls = smalls :+ word)  
  61.       else if (word.length > 7)  
  62.         copy(larges = larges :+ word)  
  63.       else  
  64.         copy(middles = middles :+ word)  
  65.     }  
  66.   
  67.     override def toString() = {  
  68.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  69.     }  
  70.   }  
  71.   
  72.   object WordsL {  
  73.     val empty = WordsL(List.empty, List.empty, List.empty)  
  74.   }  
  75.   
  76.   case class WordsVP(  
  77.     smalls: Vector[String],  
  78.     middles: Vector[String],  
  79.     larges: Vector[String]  
  80.   ) {  
  81.     def +(word: String): WordsVP = {  
  82.       if (word.length <= 3)  
  83.         copy(smalls = word +: smalls)  
  84.       else if (word.length > 7)  
  85.         copy(larges = word +: larges)  
  86.       else  
  87.         copy(middles = word +: middles)  
  88.     }  
  89.   
  90.     override def toString() = {  
  91.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  92.     }  
  93.   }  
  94.   
  95.   object WordsVP {  
  96.     val empty = WordsVP(Vector.empty, Vector.empty, Vector.empty)  
  97.   }  
  98.   
  99.   case class WordsLP(  
  100.     smalls: List[String],  
  101.     middles: List[String],  
  102.     larges: List[String]  
  103.   ) {  
  104.     def +(word: String): WordsLP = {  
  105.       if (word.length <= 3)  
  106.         copy(smalls = word :: smalls)  
  107.       else if (word.length > 7)  
  108.         copy(larges = word :: larges)  
  109.       else  
  110.         copy(middles = word :: middles)  
  111.     }  
  112.   
  113.     override def toString() = {  
  114.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  115.     }  
  116.   }  
  117.   
  118.   object WordsLP {  
  119.     val empty = WordsLP(List.empty, List.empty, List.empty)  
  120.   }  
  121.   
  122.   case class WordsSV(  
  123.     smalls: Seq[String],  
  124.     middles: Seq[String],  
  125.     larges: Seq[String]  
  126.   ) {  
  127.     def +(word: String): WordsSV = {  
  128.       if (word.length <= 3)  
  129.         copy(smalls = smalls :+ word)  
  130.       else if (word.length > 7)  
  131.         copy(larges = larges :+ word)  
  132.       else  
  133.         copy(middles = middles :+ word)  
  134.     }  
  135.   
  136.     override def toString() = {  
  137.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  138.     }  
  139.   }  
  140.   
  141.   object WordsSV {  
  142.     val empty = WordsSV(Vector.empty, Vector.empty, Vector.empty)  
  143.   }  
  144.   
  145.   case class WordsSVV(  
  146.     smalls: Seq[String],  
  147.     middles: Seq[String],  
  148.     larges: Seq[String]  
  149.   ) {  
  150.     def +(word: String): WordsSVV = {  
  151.       if (word.length <= 3)  
  152.         copy(smalls = smalls.toVector :+ word)  
  153.       else if (word.length > 7)  
  154.         copy(larges = larges.toVector :+ word)  
  155.       else  
  156.         copy(middles = middles.toVector :+ word)  
  157.     }  
  158.   
  159.     override def toString() = {  
  160.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  161.     }  
  162.   }  
  163.   
  164.   object WordsSVV {  
  165.     val empty = WordsSVV(Vector.empty, Vector.empty, Vector.empty)  
  166.   }  
  167.   
  168.   case class WordsS(  
  169.     smalls: Seq[String],  
  170.     middles: Seq[String],  
  171.     larges: Seq[String]  
  172.   ) {  
  173.     def +(word: String): WordsS = {  
  174.       if (word.length <= 3)  
  175.         copy(smalls = smalls :+ word)  
  176.       else if (word.length > 7)  
  177.         copy(larges = larges :+ word)  
  178.       else  
  179.         copy(middles = middles :+ word)  
  180.     }  
  181.   
  182.     override def toString() = {  
  183.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  184.     }  
  185.   }  
  186.   
  187.   object WordsS {  
  188.     val empty = WordsS(Seq.empty, Seq.empty, Seq.empty)  
  189.   }  
  190.   
  191.   case class WordsSP(  
  192.     smalls: Seq[String],  
  193.     middles: Seq[String],  
  194.     larges: Seq[String]  
  195.   ) {  
  196.     def +(word: String): WordsSP = {  
  197.       if (word.length <= 3)  
  198.         copy(smalls = word +: smalls)  
  199.       else if (word.length > 7)  
  200.         copy(larges = word +: larges)  
  201.       else  
  202.         copy(middles = word +: middles)  
  203.     }  
  204.   
  205.     override def toString() = {  
  206.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  207.     }  
  208.   }  
  209.   
  210.   object WordsSP {  
  211.     val empty = WordsSP(Seq.empty, Seq.empty, Seq.empty)  
  212.   }  
  213.   
  214.   case class WordsIV(  
  215.     smalls: IndexedSeq[String],  
  216.     middles: IndexedSeq[String],  
  217.     larges: IndexedSeq[String]  
  218.   ) {  
  219.     def +(word: String): WordsIV = {  
  220.       if (word.length <= 3)  
  221.         copy(smalls = smalls :+ word)  
  222.       else if (word.length > 7)  
  223.         copy(larges = larges :+ word)  
  224.       else  
  225.         copy(middles = middles :+ word)  
  226.     }  
  227.   
  228.     override def toString() = {  
  229.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  230.     }  
  231.   }  
  232.   
  233.   object WordsIV {  
  234.     val empty = WordsIV(Vector.empty, Vector.empty, Vector.empty)  
  235.   }  
  236.   
  237.   case class WordsIA(  
  238.     smalls: IndexedSeq[String],  
  239.     middles: IndexedSeq[String],  
  240.     larges: IndexedSeq[String]  
  241.   ) {  
  242.     def +(word: String): WordsIA = {  
  243.       if (word.length <= 3)  
  244.         copy(smalls = smalls :+ word)  
  245.       else if (word.length > 7)  
  246.         copy(larges = larges :+ word)  
  247.       else  
  248.         copy(middles = middles :+ word)  
  249.     }  
  250.   
  251.     override def toString() = {  
  252.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  253.     }  
  254.   }  
  255.   
  256.   object WordsIA {  
  257.     val empty = WordsIA(Array[String](), Array[String](), Array[String]())  
  258.   }  
  259.   
  260.   case class WordsI(  
  261.     smalls: IndexedSeq[String],  
  262.     middles: IndexedSeq[String],  
  263.     larges: IndexedSeq[String]  
  264.   ) {  
  265.     def +(word: String): WordsI = {  
  266.       if (word.length <= 3)  
  267.         copy(smalls = smalls :+ word)  
  268.       else if (word.length > 7)  
  269.         copy(larges = larges :+ word)  
  270.       else  
  271.         copy(middles = middles :+ word)  
  272.     }  
  273.   
  274.     override def toString() = {  
  275.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  276.     }  
  277.   }  
  278.   
  279.   object WordsI {  
  280.     val empty = WordsI(IndexedSeq.empty, IndexedSeq.empty, IndexedSeq.empty)  
  281.   }  
  282.   
  283.   case class WordsIP(  
  284.     smalls: IndexedSeq[String],  
  285.     middles: IndexedSeq[String],  
  286.     larges: IndexedSeq[String]  
  287.   ) {  
  288.     def +(word: String): WordsIP = {  
  289.       if (word.length <= 3)  
  290.         copy(smalls = word +: smalls)  
  291.       else if (word.length > 7)  
  292.         copy(larges = word +: larges)  
  293.       else  
  294.         copy(middles = word +: middles)  
  295.     }  
  296.   
  297.     override def toString() = {  
  298.       s"small:smalls.length,middle:{middles.length}, large:${larges.length}"  
  299.     }  
  300.   }  
  301.   
  302.   object WordsIP {  
  303.     val empty = WordsIP(IndexedSeq.empty, IndexedSeq.empty, IndexedSeq.empty)  
  304.   }  
  305.   
  306.   class WordsBuilderV {  
  307.     private val smalls = new ArrayBuffer[String]  
  308.     private val middles = new ArrayBuffer[String]  
  309.     private val larges = new ArrayBuffer[String]  
  310.   
  311.     def +(word: String): WordsBuilderV = {  
  312.       if (word.length <= 3)  
  313.         smalls += word  
  314.       else if (word.length > 7)  
  315.         larges += word  
  316.       else  
  317.         middles += word  
  318.       this  
  319.     }  
  320.   
  321.     def toWords = WordsV(smalls.toVector, middles.toVector, larges.toVector)  
  322.   }  
  323.   
  324.   class WordsBuilderL {  
  325.     private val smalls = new ArrayBuffer[String]  
  326.     private val middles = new ArrayBuffer[String]  
  327.     private val larges = new ArrayBuffer[String]  
  328.   
  329.     def +(word: String): WordsBuilderL = {  
  330.       if (word.length <= 3)  
  331.         smalls += word  
  332.       else if (word.length > 7)  
  333.         larges += word  
  334.       else  
  335.         middles += word  
  336.       this  
  337.     }  
  338.   
  339.     def toWords = WordsL(smalls.toList, middles.toList, larges.toList)  
  340.   }  
  341.   
  342.   class WordsBuilderS {  
  343.     private val smalls = new ArrayBuffer[String]  
  344.     private val middles = new ArrayBuffer[String]  
  345.     private val larges = new ArrayBuffer[String]  
  346.   
  347.     def +(word: String): WordsBuilderS = {  
  348.       if (word.length <= 3)  
  349.         smalls += word  
  350.       else if (word.length > 7)  
  351.         larges += word  
  352.       else  
  353.         middles += word  
  354.       this  
  355.     }  
  356.   
  357.     def toWords = WordsS(smalls, middles, larges)  
  358.   }  
  359.   
  360.   def go[T](label: String)(body: => T) {  
  361.     val start = System.currentTimeMillis  
  362.     try {  
  363.       val r = body  
  364.       val result = r match {  
  365.         case x: Try[_] => x.toString  
  366.         case x: Task[_] => x.toString  
  367.         case x => x.toString  
  368.       }  
  369.       val end = System.currentTimeMillis  
  370.       println(s"label({end - start}): ${result}")  
  371.     } catch {  
  372.       case e: Throwable =>  
  373.         val end = System.currentTimeMillis  
  374.       println(s"label({end - start}): ${e}")  
  375.     }  
  376.   }  
  377.   
  378.   import scalax.io.{Resource, Codec}  
  379.   
  380.   def main(args: Array[String]) {  
  381.     import Words.getTokens  
  382.     implicit val codec = Codec.UTF8  
  383.     val filename = "PrincesOfMars.txt"  
  384.     val inputs = Resource.fromFile(filename).lines().  
  385.       map(getTokens).  
  386.       foldLeft(new ArrayBuffer[String])(_ ++ _)  
  387.     go("WordsJ") {  
  388.       inputs.foldLeft(new WordsJ)(_ + _)  
  389.     }  
  390.     go("WordsV") {  
  391.       inputs.foldLeft(WordsV.empty)(_ + _)  
  392.     }  
  393.     go("WordsVP") {  
  394.       inputs.foldLeft(WordsVP.empty)(_ + _)  
  395.     }  
  396.     go("WordsL") {  
  397.       inputs.foldLeft(WordsL.empty)(_ + _)  
  398.     }  
  399.     go("WordsLP") {  
  400.       inputs.foldLeft(WordsLP.empty)(_ + _)  
  401.     }  
  402.     go("WordsS") {  
  403.       inputs.foldLeft(WordsS.empty)(_ + _)  
  404.     }  
  405.     go("WordsSP") {  
  406.       inputs.foldLeft(WordsSP.empty)(_ + _)  
  407.     }  
  408.     go("WordsSV") {  
  409.       inputs.foldLeft(WordsSV.empty)(_ + _)  
  410.     }  
  411.     go("WordsSVV") {  
  412.       inputs.foldLeft(WordsSVV.empty)(_ + _)  
  413.     }  
  414.     go("WordsI") {  
  415.       inputs.foldLeft(WordsI.empty)(_ + _)  
  416.     }  
  417.     go("WordsIP") {  
  418.       inputs.foldLeft(WordsIP.empty)(_ + _)  
  419.     }  
  420.     go("WordsIV") {  
  421.       inputs.foldLeft(WordsIV.empty)(_ + _)  
  422.     }  
  423.     go("WordsIA") {  
  424.       inputs.foldLeft(WordsIA.empty)(_ + _)  
  425.     }  
  426.     go("WordsBuilderV") {  
  427.       inputs.foldLeft(new WordsBuilderV)(_ + _).toWords  
  428.     }  
  429.     go("WordsBuilderL") {  
  430.       inputs.foldLeft(new WordsBuilderL)(_ + _).toWords  
  431.     }  
  432.     go("WordsBuilderS") {  
  433.       inputs.foldLeft(new WordsBuilderS)(_ + _).toWords  
  434.     }  
  435.   }  
  436. }  

諸元

  • Mac OS 10.7.5 (2.6 GHz Intel Core i7)
  • Java 1.7.0_75
  • Scala 2.11.6