Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: optimize the http.ContentType method #3363

Merged
merged 2 commits into from
Aug 19, 2024

Conversation

1911860538
Copy link
Contributor

Improve performance and readability, concatenating strings with "+" instead of strings.Join.

Below is my local test code:

http.go

package httputil

import (
	"strings"
)

const (
	baseContentType = "application"
)

// ContentType returns the content-type with base prefix.
func ContentType(subtype string) string {
	return strings.Join([]string{baseContentType, subtype}, "/")
}

func NewContentType(subtype string) string {
	return baseContentType + "/" + subtype
}

http_test.go

package httputil

import (
	"testing"
)

func TestContentTypeSame(t *testing.T) {
	subtypes := [...]string{"x-www-form-urlencoded", "json"}
	for _, subtype := range subtypes {
		contentType := ContentType(subtype)
		newContentType := NewContentType(subtype)
		if contentType != newContentType {
			t.Fatalf("got different content type, expected %s got %s", contentType, newContentType)
		}
	}
}

func BenchmarkContentType(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		ContentType("json")
	}
}

func BenchmarkNewContentType(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		NewContentType("json")
	}
}

test output

=== RUN   TestContentTypeSame
--- PASS: TestContentTypeSame (0.00s)
PASS

Process finished with the exit code 0

bench output

goos: darwin
goarch: arm64
pkg: github.com/go-kratos/kratos/v2/internal/httputil
BenchmarkContentType
BenchmarkContentType-11       	57805406	        20.32 ns/op	      16 B/op	       1 allocs/op
BenchmarkNewContentType
BenchmarkNewContentType-11    	100000000	        10.02 ns/op	       0 B/op	       0 allocs/op
PASS

Process finished with the exit code 0

@dosubot dosubot bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jul 12, 2024
@dosubot dosubot bot added the LGTM label Aug 16, 2024
@shenqidebaozi shenqidebaozi merged commit 2f94905 into go-kratos:main Aug 19, 2024
33 checks passed
@1911860538 1911860538 deleted the feat/httputil branch August 19, 2024 07:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
LGTM size:XS This PR changes 0-9 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants