If you have any questions or suggestions, please contact us in time. My official account is “Brain fried Fish”, GitHub address: github.com/eddycjy.

Hello, I’m fried fish.

Len == 0 and string == “”, what’s the difference? “

This is a relatively small detail point, but also aroused my curiosity, so this article will study with you whether there is a difference between them. Which one has better performance?

The test method

In the test method, we declare Test1 and Test2 methods, respectively:

func Test1() bool { var v string if v == "" { return true } return false } func Test2() bool { var v string if len(v) ==  0 { return true } return false }Copy the code

Inside the method is a simple variable type declaration, based on the string == “” and the string len == 0.

The test case

Write benchmarks for two methods for subsequent performance tests:

func BenchmarkTest1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Test1()
	}
}

func BenchmarkTest2(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Test2()
	}
}
Copy the code

Results analysis

$ go test --bench=. -benchmem goos: darwin goarch: Amd64 benchmarkTest1-4 1000000000 0.305 NS /op 0 B/op 0 ALLOCs /op benchmarkTest2-4 1000000000 0.305 NS /op 0 B/op 0 Allocs/op PASS ok _ / Users/eddycjy/go - application/awesomeProject/tests 0.688 sCopy the code

From the results of multiple tests, the two are compared:

  • Performance is almost indistinguishable, and even identical.
  • All values are 0/ OP and do not involve memory application or operation. The Go compiler optimizes the initialization of a variable after it is declared.

It turned out to be the same. We can take a closer look at their assembly code to see what the specific differences are:

$ go tool compile -S main.go "".main STEXT nosplit size=1 args=0x0 locals=0x0 0x0000 00000 (main.go:3) TEXT "".main(SB),  NOSPLIT|ABIInternal, $0-0 0x0000 00000 (main.go:3) FUNCDATA $0, Gclocals · 33 cdeccccebe80329f1fdbee7f5874cb (SB) 0 x0000 00000 (main) go: 3) FUNCDATA $1. Gclocals · 33 cdeccccebe80329f1fdbee7f5874cb (SB) 0 x0000 00000 (main) go: 5) RET 0 x0000 c3. Go. Cuinfo. Packagename. SDWARFINFO  dupok size=0 0x0000 6d 61 69 6e main "".. inittask SNOPTRDATA size=24 0x0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0x0010 00 00 00 00 00 00 00 00 ........ Gclocals · 33 cdeccccebe80329f1fdbee7f5874cb SRODATA dupok x0000 size = 8 0 01 00 00 00 00 00 00 00Copy the code

Whether len(v) == 0 or v == “”, the compiled assembly code is exactly the same. It is clear that the Go compiler has explicitly optimized this area, most likely directly.

Do you have any other views and expansion? Welcome to study and exchange with us.

My official account

Share Go language, micro service architecture and strange system design, welcome to pay attention to my public number and I exchange and communication.

The best relationship is mutual achievement. Your praise is the biggest motivation for the creation of fried fish. Thank you for your support.