Groovyで文字列の末尾に文字列を追加する


文字列の末尾に文字列を追加するには、String#concat()、+演算子、< でStringBufferに
よる結合がある。

コード

test1 = "abc"
test2=test1.concat("def")
println test1
println test2
println test1.class
println test2.class


test3 = ""
test3 <<= "abc"
test3 <<= "def"
println test3
println test3.class

test4 = "abc"
test4 += "def"
println test4
println test4.class

実行結果

abc
abcdef
class java.lang.String
class java.lang.String
abcdef
class java.lang.StringBuffer
abcdef
class java.lang.String

性能

+で結合
(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..1000).each{
        buf <<= "xxx|"
    }
    end =  System.currentTimeMillis();
    println end - start
}

(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..10000).each{
        buf <<= "xxx|"
    }
    end =  System.currentTimeMillis();
    println end - start
}
[D:\workspace\groovy_SandBox]groovy Q60_文字列の末尾に文字列を追加する_性能1.groovy
78
63
31
47
31
5656
5531
5641
5656
5859
concat
(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..1000).each{
        buf+= buf.concat("xxx|")
    }
    end =  System.currentTimeMillis();
    println end - start
}


(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..10000).each{
        buf+= buf.concat("xxx|")
    }
    end =  System.currentTimeMillis();
    println end - start
}
[D:\workspace\groovy_SandBox]groovy Q60_文字列の末尾に文字列を追加する_性能2.groovy
Caught: java.lang.OutOfMemoryError: Java heap space
        at Q60_文字列の末尾に文字列を追加する_性能2$_run_closure1_closure3.doCall(Q60_文字列の末尾に文字列を追加する_性能2.groovy:7)
        at Q60_文字列の末尾に文字列を追加する_性能2$_run_closure1.doCall(Q60_文字列の末尾に文字列を追加する_性能2.groovy:6)
StringBufferで結合
(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..1000).each{
        buf += "xxx|"
    }
    end =  System.currentTimeMillis();
    println end - start
}

(1..5).each{
    buf = ""
    start = System.currentTimeMillis();
    (1..10000).each{
        buf += "xxx|"
    }
    end =  System.currentTimeMillis();
    println end - start
}
47
31
0
0
0
46
16
47
16
31

Javaで取得できるミリ秒って16msでそれ以下だと0になったような気がする。


Rubyとは逆で、Javaの場合は、+よりもconcat()の方がメモリを食うようだ。
速度は、圧倒的にStringBufferが早い。
とにかく、Javaと同じくGroovyでも、StringBufferを使えということだな。





添削歓迎

ここ間違ってるよ
こうした方がGroovyらしくないか?
などなど
方法は、コメント、トラックバックはてブTwitter @orange_clover宛 で、お願いしまます。

実行環境






Groovyの詳細についてはJavadocと以下の書籍を参考にしている。




Dierk Konig、Andrew Glover、Paul King、、Guillaume Laforge、Jon Skeet、杉浦 孝、櫻井 正樹、須江 信洋、関谷 和愛、佐野 徹郎、寺沢 尚史

Amazonでご確認ください。



問題自体は第2版のもの。rubyと似てる部分も多いので、ヒントにもなる。
写経でもいいが自分で考えるために他言語の例をGroovyで置き換えてる。




青木 峰郎、後藤 裕蔵、高橋 征義、まつもと ゆきひろ

価格: ¥ 2,940
価格は記載時点のものです。購入前にAmazonでご確認ください。




Groovyイン・アクションを読むならあった方が便利かな。

Rubyレシピブックは「ほんたった」で立ててる