string_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package runtime_test
  5. import (
  6. "testing"
  7. )
  8. func BenchmarkCompareStringEqual(b *testing.B) {
  9. bytes := []byte("Hello Gophers!")
  10. s1, s2 := string(bytes), string(bytes)
  11. for i := 0; i < b.N; i++ {
  12. if s1 != s2 {
  13. b.Fatal("s1 != s2")
  14. }
  15. }
  16. }
  17. func BenchmarkCompareStringIdentical(b *testing.B) {
  18. s1 := "Hello Gophers!"
  19. s2 := s1
  20. for i := 0; i < b.N; i++ {
  21. if s1 != s2 {
  22. b.Fatal("s1 != s2")
  23. }
  24. }
  25. }
  26. func BenchmarkCompareStringSameLength(b *testing.B) {
  27. s1 := "Hello Gophers!"
  28. s2 := "Hello, Gophers"
  29. for i := 0; i < b.N; i++ {
  30. if s1 == s2 {
  31. b.Fatal("s1 == s2")
  32. }
  33. }
  34. }
  35. func BenchmarkCompareStringDifferentLength(b *testing.B) {
  36. s1 := "Hello Gophers!"
  37. s2 := "Hello, Gophers!"
  38. for i := 0; i < b.N; i++ {
  39. if s1 == s2 {
  40. b.Fatal("s1 == s2")
  41. }
  42. }
  43. }
  44. func BenchmarkCompareStringBigUnaligned(b *testing.B) {
  45. bytes := make([]byte, 0, 1<<20)
  46. for len(bytes) < 1<<20 {
  47. bytes = append(bytes, "Hello Gophers!"...)
  48. }
  49. s1, s2 := string(bytes), "hello"+string(bytes)
  50. for i := 0; i < b.N; i++ {
  51. if s1 != s2[len("hello"):] {
  52. b.Fatal("s1 != s2")
  53. }
  54. }
  55. b.SetBytes(int64(len(s1)))
  56. }
  57. func BenchmarkCompareStringBig(b *testing.B) {
  58. bytes := make([]byte, 0, 1<<20)
  59. for len(bytes) < 1<<20 {
  60. bytes = append(bytes, "Hello Gophers!"...)
  61. }
  62. s1, s2 := string(bytes), string(bytes)
  63. for i := 0; i < b.N; i++ {
  64. if s1 != s2 {
  65. b.Fatal("s1 != s2")
  66. }
  67. }
  68. b.SetBytes(int64(len(s1)))
  69. }