Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created January 27, 2015 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahitojp/bcf0fad918db4c57495a to your computer and use it in GitHub Desktop.
Save masahitojp/bcf0fad918db4c57495a to your computer and use it in GitHub Desktop.
parindromeかを判定する関数を複数パターン作って、一番早い書き方を調査
package main
import "unicode/utf8"
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func IsPalindrome(s string) bool {
return s == Reverse(s)
}
func IsPalindrome2(s string) bool {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
if runes[i] != runes[j] {
return false
}
}
return true
}
func IsPalindrome3(s string) bool {
l := len(s)
for i, w := 0, 0; i < l; i += w {
runeValue1, width := utf8.DecodeRuneInString(s[i:])
runeValue2, width := utf8.DecodeLastRuneInString(s[:l-i])
if runeValue1 != runeValue2 {
return false
}
w = width
}
return true
}
func IsPalindrome4(s string) bool {
l := len(s)
for i, runeValue := range s {
runeValue2, _ := utf8.DecodeLastRuneInString(s[:l-i])
if runeValue != runeValue2 {
return false
}
}
return true
}
func main() {
for i := 0; i < 1000000; i++ {
IsPalindrome4("しんぶんし")
}
}
package main
import "testing"
var s = "あいういあ"
func BenchmarkIsPalindrome(b *testing.B) {
for i := 0; i < b.N; i++ {
IsPalindrome(s)
}
}
func BenchmarkIsPalindrome2(b *testing.B) {
for i := 0; i < b.N; i++ {
IsPalindrome2(s)
}
}
func BenchmarkIsPalindrome3(b *testing.B) {
for i := 0; i < b.N; i++ {
IsPalindrome3(s)
}
}
func BenchmarkIsPalindrome4(b *testing.B) {
for i := 0; i < b.N; i++ {
IsPalindrome4(s)
}
}
func TestIsKaibun(t *testing.T) {
actual := IsPalindrome4(s)
expected := true
if actual != expected {
t.Errorf("got %v\nwant %v", actual, expected)
}
}
func TestIsKaibunFalse(t *testing.T) {
actual := IsPalindrome4("あいういう")
expected := false
if actual != expected {
t.Errorf("got %v\nwant %v", actual, expected)
}
}
AMD FX-8120 3.1GHz[AM3+/8Core/125W]
memory 32GiB
ArchLinux
% go version
go version go1.4.1 linux/amd64
% go test -bench .
PASS
BenchmarkIsPalindrome 3000000 544 ns/op
BenchmarkIsPalindrome2 5000000 277 ns/op
BenchmarkIsPalindrome3 10000000 202 ns/op
BenchmarkIsPalindrome4 10000000 199 ns/op
ok _/home/masahito/src/golang/perindrome 8.287s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment