LoginSignup
71
55

More than 5 years have passed since last update.

Go言語でのString・Int間の変換速度について

Last updated at Posted at 2015-06-05

※ 追記 reflectの使い方が間違っていたので訂正しました。切腹...m(__)m

いくつか書き方があるようなので、簡単な比較をしてみました。

ベンチに使ったコードは下記にあります

文字列から数値(String to Int)

文字列から数値に変換する方法

strconv.Atoi(string) int, error

// 引数は 変換対称の文字列, 基数, ビット数
strconv.ParseInt(string, int, int) int64, error

ベンチマーク結果

// 小さな数値文字列で計測 (n = 35)
BenchmarkAtoi                   50000000           28.6 ns/op         0 B/op           0 allocs/op
BenchmarkAtoiParseInt           50000000           27.0 ns/op         0 B/op           0 allocs/op

// とても大きな数値文字列で計測 (n = 999,999,999,999)
BenchmarkAtoiBig                20000000           57.2 ns/op         0 B/op           0 allocs/op
BenchmarkAtoiParseIntBig        30000000           54.6 ns/op         0 B/op           0 allocs/op

結論

どちらもそこまで変わらないので、10進数であれば簡単な strconv.Atoi(string) を使う感じでしょうか?

  • 戻り値の型がint で欲しい場合は strconv.Atoi(string)
  • 戻り値の型がint64 で欲しい場合は strconv.ParseInt(string, 10, 64)

を使えば良さそう。

数値から文字列(Int to String)

数値から文字列に変換する方法


strconv.Itoa(int) string

// 引数は 変換対称の数値, 基数
strconv.FormatInt(int64, int) string

fmt.Sprint(int) string
fmt.Sprintf("%d", int) string

ベンチマーク結果

// 小さな数値で計測 (n = 35)
BenchmarkItoa                           30000000           52.6 ns/op         2 B/op           1 allocs/op
BenchmarkItoaFormatInt                  30000000           52.5 ns/op         2 B/op           1 allocs/op
BenchmarkItoaSprint                     5000000            254 ns/op          16 B/op          2 allocs/op
BenchmarkItoaSprintf                    5000000            299 ns/op          16 B/op          2 allocs/op

// とても大きな数値で計測 (n = 999,999,999,999)
BenchmarkItoaBig                        10000000           140 ns/op          16 B/op          1 allocs/op
BenchmarkItoaFormatIntBig               10000000           118 ns/op          16 B/op          1 allocs/op
BenchmarkItoaSprintBig                  5000000            326 ns/op          24 B/op          2 allocs/op
BenchmarkItoaSprintfBig                 5000000            363 ns/op          24 B/op          2 allocs/op

結論

  • 型がわかっている場合は strconv.Itoa(int)strconv.FormatInt(int64, 10)
  • fmt.Sprint() は型が分からないときに使うと良さそう

といった感じなんでしょうか。

71
55
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
71
55