Skip to content

Conversation

1911860538
Copy link
Contributor

Replaced strings.SplitN with strings.Cut to reduce allocations and improve performance.
Below is my local test code.
join_test.go

package gorm

import (
	"strings"
	"testing"
)

func original(join string) (join0, join1 string, cut bool) {
	joins := strings.SplitN(join, ".", 2)
	if len(joins) == 2 {
		return joins[0], joins[1], true
	}
	return "", "", false
}

func optimized(join string) (join0, join1 string, cut bool) {
	join0, join1, cut = strings.Cut(join, ".")
	if cut {
		return join0, join1, cut
	}
	return "", "", false
}

func Benchmark_join(b *testing.B) {
	join := "a.b"

	b.Run("original", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			original(join)
		}
	})

	b.Run("optimized", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			optimized(join)
		}
	})
}

benchmark output

goos: darwin
goarch: amd64
pkg: testgolang/gorm
cpu: Intel(R) Core(TM) i7-8569U CPU @ 2.80GHz
Benchmark_join
Benchmark_join/original
Benchmark_join/original-8         	27360766	        40.37 ns/op	      32 B/op	       1 allocs/op
Benchmark_join/optimized
Benchmark_join/optimized-8        	158664487	         7.664 ns/op	       0 B/op	       0 allocs/op
PASS

Process finished with the exit code 0

@jinzhu jinzhu merged commit 1c966e0 into go-gorm:master May 21, 2025
39 of 42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants