douchaqi3369 2013-11-27 02:47
浏览 88
已采纳

Go如何进行字符串比较?

http://golang.org/ref/spec#Comparison_operators

Go supports string comparison without any special functions. Does the Go runtime do work behind the scenes to make comparisons of string literals?

  • 写回答

2条回答 默认 最新

  • douyanjing0822 2013-11-27 06:11
    关注

    As you can see in the following assembly dump, string comparison is delegated to a runtime.eqstring function from the runtime (line 17) after a short circuit check to see if the two operands are the same in-memory string (line 11):

    $ cat foo.go
    package main
    
    func 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-0
    0001 (foo.go:3) LOCALS  ,$0
    0002 (foo.go:4) LEAQ    go.string."hello"+0(SB),BX
    0003 (foo.go:4) MOVQ    (BX),SI
    0004 (foo.go:4) MOVQ    8(BX),CX
    0005 (foo.go:5) LEAQ    go.string."world"+0(SB),BX
    0006 (foo.go:5) MOVQ    (BX),DX
    0007 (foo.go:5) MOVQ    8(BX),AX
    0008 (foo.go:6) JMP     ,11
    0009 (foo.go:6) MOVQ    $1,AX
    0010 (foo.go:6) JMP     ,23
    0011 (foo.go:6) CMPQ    CX,AX
    0012 (foo.go:6) JNE     ,22
    0013 (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),BX
    0019 (foo.go:6) CMPB    BX,$0
    0020 (foo.go:6) JEQ     ,22
    0021 (foo.go:6) JMP     ,9
    0022 (foo.go:6) MOVQ    $0,AX
    0023 (foo.go:7) RET     ,
    
    --- prog list "init" ---
    0024 (foo.go:7) TEXT    init+0(SB),$0-0
    0025 (foo.go:7) MOVBQZX initdone·+0(SB),AX
    0026 (foo.go:7) LOCALS  ,$0
    0027 (foo.go:7) CMPB    AX,$0
    0028 (foo.go:7) JEQ     ,34
    0029 (foo.go:7) CMPB    AX,$2
    0030 (foo.go:7) JNE     ,32
    0031 (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     ,
    

    Unless you are working on the compiler or runtime, this shouldn't concern you too much: just use the operators as the spec defines, and expect that the comparison to be O(n) with the length of the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比