JavaScriptの文字列結合についてまとめました.
JavaだとStringBuilderを使うというように、文字列結合は単純に行うと性能が出ないことがあります.
結論から言うと、JavaScriptではあまり考えなくてよさそうです.
- JavaScriptでは何も考えずに変数宣言時に+演算子で結合する
- 変数宣言と+演算子での結合のみを分ける
参考: JavaScriptのパフォーマンス文字列結合
* グラフはops/sec (1秒あたりの実行回数)を示しているので、バーが伸びているほど高速です.
直接結合する |
|
<span class="kw2">var</span> foo <span class="sy0">=</span> <span class="st0">'a'</span> <span class="sy0">+</span> <span class="st0">'b'</span> <span class="sy0">+</span> <span class="st0">'c'</span> <span class="sy0">+</span> <span class="st0">'d'</span><span class="sy0">;</span> |
|
各値を+=で結合する
|
|
<span class="kw2">var</span> foo <span class="sy0">=</span> <span class="st0">'a'</span><span class="sy0">;</span> foo <span class="sy0">+=</span> <span class="st0">'b'</span><span class="sy0">;</span> foo <span class="sy0">+=</span> <span class="st0">'c'</span><span class="sy0">;</span> foo <span class="sy0">+=</span> <span class="st0">'d'</span><span class="sy0">;</span> |
|
再代入を繰り返す
|
|
<span class="kw2">var</span> foo <span class="sy0">=</span> <span class="st0">'a'</span><span class="sy0">;</span> foo <span class="sy0">=</span> foo <span class="sy0">+</span> <span class="st0">'b'</span><span class="sy0">;</span> foo <span class="sy0">=</span> foo <span class="sy0">+</span> <span class="st0">'c'</span><span class="sy0">;</span> foo <span class="sy0">=</span> foo <span class="sy0">+</span> <span class="st0">'d'</span><span class="sy0">;</span> |
|
Array#joinを利用する
|
|
<span class="kw2">var</span> foo <span class="sy0">=</span> arr.<span class="me1">join</span><span class="br0">(</span><span class="st0">''</span><span class="br0">)</span><span class="sy0">;</span> |
|
変数を宣言したあと、1行で結合する |
|
<span class="kw2">var</span> foo <span class="sy0">=</span> <span class="st0">'a'</span><span class="sy0">;</span> foo <span class="sy0">+=</span> <span class="st0">'b'</span> <span class="sy0">+</span> <span class="st0">'c'</span> <span class="sy0">+</span> <span class="st0">'d'</span><span class="sy0">;</span> |
|
関数で文字列の配列を結合する
|
|
<span class="kw2">function</span> concat<span class="br0">(</span>arr<span class="br0">)</span> <span class="br0">{</span> len <span class="sy0">=</span> arr.<span class="me1">length</span><span class="sy0">;</span> <span class="kw1">for</span> <span class="br0">(</span>s <span class="sy0">=</span> <span class="st0">""</span><span class="sy0">,</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0"><</span> len<span class="sy0">;</span> s <span class="sy0">+=</span> arr<span class="br0">[</span>i<span class="br0">]</span><span class="sy0">,</span> i<span class="sy0">++</span><span class="br0">)</span><span class="sy0">;</span> <span class="kw1">return</span> s<span class="sy0">;</span> <span class="br0">}</span> <span class="kw2">var</span> foo <span class="sy0">=</span> concat<span class="br0">(</span>arr<span class="br0">)</span><span class="sy0">;</span> |
|