開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES) (Alan A.A. Donovan(著)、Brian W. Kernighan(著)、柴田 芳樹(翻訳)、丸善出版)の第1章(チュートリアル)、1.2(コマンドライン引数)、練習問題1.3の解答を求めてみる。
コード
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
s1, s2 := 0.0, 0.0
// forループ
start := time.Now()
s, sep := "", ""
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)
s1 = time.Since(start).Seconds()
fmt.Println("%.2fs", s1)
start = time.Now()
fmt.Println(strings.Join(os.Args[1:], " "))
s2 = time.Since(start).Seconds()
fmt.Println("%.2fs", s2)
fmt.Println("事項時間の差(forループ - strings.Join関数): %.2fs", s1-s2)
}
入出力結果(Terminal, cmd(コマンドプロンプト))
$ go run sample3.go %.2fs 2.7569e-05 %.2fs 2.021e-06 事項時間の差(forループ - strings.Join関数): %.2fs 2.5548e-05 $ go run sample3.go 1 1 %.2fs 2.7631e-05 1 %.2fs 2.055e-06 事項時間の差(forループ - strings.Join関数): %.2fs 2.5576e-05 $ go run sample3.go 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 %.2fs 2.841e-05 1 2 3 4 5 6 7 8 9 10 %.2fs 2.625e-06 事項時間の差(forループ - strings.Join関数): %.2fs 2.5785e-05 $ go run sample3.go a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z %.2fs 2.9439e-05 a b c d e f g h i j k l m n o p q r s t u v w x y z %.2fs 2.874e-06 事項時間の差(forループ - strings.Join関数): %.2fs 2.6565e-05 $ go run sample3.go a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z %.2fs 5.9824e-05 a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z %.2fs 4.199e-06 事項時間の差(forループ - strings.Join関数): %.2fs 5.5625000000000004e-05 $
このコードの場合はstrings.Joinを使ったバージョンの方が速い結果に。forとrangeを使った方がインデックスの取得と文字列の連結の演算があるから時間がかかると予想。
ということで、性能、コードの短さ、読みやすさのいずれを考慮してもforループとrangeを使ったコードよりstrings.Joinを使ったコードの方が良さそう。
0 コメント:
コメントを投稿