慕后森
正如您在以下程序集转储中看到的那样,runtime.eqstring在进行短路检查以查看两个操作数是否是相同的内存中字符串(第 11 行)之后,字符串比较被委托给运行时(第 17 行)中的一个函数:$ cat foo.gopackage mainfunc main() { a := "hello" b := "world" _ = a == b}$ go tool 6g -S foo.go--- prog list "main" ---0000 (foo.go:3) TEXT main+0(SB),$40-00001 (foo.go:3) LOCALS ,$00002 (foo.go:4) LEAQ go.string."hello"+0(SB),BX0003 (foo.go:4) MOVQ (BX),SI0004 (foo.go:4) MOVQ 8(BX),CX0005 (foo.go:5) LEAQ go.string."world"+0(SB),BX0006 (foo.go:5) MOVQ (BX),DX0007 (foo.go:5) MOVQ 8(BX),AX0008 (foo.go:6) JMP ,110009 (foo.go:6) MOVQ $1,AX0010 (foo.go:6) JMP ,230011 (foo.go:6) CMPQ CX,AX0012 (foo.go:6) JNE ,220013 (foo.go:6) MOVQ SI,(SP)0014 (foo.go:6) MOVQ CX,8(SP)0015 (foo.go:6) MOVQ DX,16(SP)0016 (foo.go:6) MOVQ AX,24(SP)0017 (foo.go:6) CALL ,runtime.eqstring+0(SB)0018 (foo.go:6) MOVBQZX 32(SP),BX0019 (foo.go:6) CMPB BX,$00020 (foo.go:6) JEQ ,220021 (foo.go:6) JMP ,90022 (foo.go:6) MOVQ $0,AX0023 (foo.go:7) RET ,--- prog list "init" ---0024 (foo.go:7) TEXT init+0(SB),$0-00025 (foo.go:7) MOVBQZX initdone·+0(SB),AX0026 (foo.go:7) LOCALS ,$00027 (foo.go:7) CMPB AX,$00028 (foo.go:7) JEQ ,340029 (foo.go:7) CMPB AX,$20030 (foo.go:7) JNE ,320031 (foo.go:7) RET ,0032 (foo.go:7) CALL ,runtime.throwinit+0(SB)0033 (foo.go:7) UNDEF ,0034 (foo.go:7) MOVB $2,initdone·+0(SB)0035 (foo.go:7) RET ,除非您正在处理编译器或运行时,否则您不必担心太多:只需使用规范定义的运算符,并期望与字符串长度的比较为 O(n)。