doushou1298 2018-06-11 07:50
浏览 111

在golang中使用==符号并使用循环比较字符串a是否等于字符串b,哪个性能更好?

for i:=0;i<len(a);i++{
    if a[i] != b[i]{
        return false
    }
}

and just

a == b

I've found that the same string have different address

a := "abc"
b := "abc"
println(&a)
println(&b)

answer is :
0xc420045f68
0xc420045f58

so == not using address to compare.
In fact, I would like to know how == compares two strings.
I am searching for a long time on net. But failed...

  • 写回答

2条回答 默认 最新

  • ds11111111111111111 2018-06-11 08:07
    关注

    You should use the == operator to compare strings. It compares the content of the string values.

    What you print is the address of a and b variables. Since they are 2 distinct non-zero size variables, their addresses cannot be the same by definition. The values they hold of course may or may not be the same. The == operator compares the values the variables hold, not the addresses of the variables.

    Your solution with the loop might even result in a runtime panic, if the b string is shorter than a, as you index it with values that are valid for a.

    The built-in == operator will likely always outperform any loop, as that is implemented in architecture specific assembly code. It is implemented in the runtime package, unexported function memequal().

    Also note that the built-in comparison might even omit checking the actual contents of the texts if their string header points to the same data (and have equal length). There is no reason not to use ==.

    The only reason where a custom equal function for string values would make sense is where the heuristics of your strings are known. E.g. if you know all the string values have the same prefix and they may only differ in their last character. In this case you could write a comparator function which only compares the last character of the strings to decide if they are equal (and only, optionally revert to actually compare the rest). This solution would of course not use a loop.

    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败