GolangNote

Golang笔记

Golang字符串相等比较的性能

Permalink2

在 golang 里判断字符串是否相等,最简单的方法就是用==判断,如果要提高性能,就使用strings.Compare

如下:

Go: 判断字符串是否相等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main(){
	fmt.Println(strings.Compare("golang","GoLang"))
	fmt.Println(strings.Compare("GoLang","golang"))
	fmt.Println(strings.Compare("golang","golang"))

	fmt.Println(strings.EqualFold("GoLang","golang"))
	fmt.Println(strings.EqualFold("golang","GoLang"))
}

输出:

plaintext: 判断字符串是否相等输出
1
2
3
4
5
1
-1
0
true
true

使用 strings.Compare 比较两个字符串的结果有三:1,0,-1

strings.Compare

strings.EqualFold 是忽略大小写的比较,返回bool

strings.EqualFold

本文网址: https://golangnote.com/topic/250.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Comments

There are 2 Comments to "Golang字符串相等比较的性能"

1 HDJ says:
回复

可是strings.Compare也是用==的方式判断的呀

2 GolangNote says:
回复

@HDJ #1 官方SDK注释说明了,代码看起来是相同,但编译过程稍不同, strings.Compare 方法不会调用 runtimecmpstring 方法所以快。

Write a Comment to "Golang字符串相等比较的性能"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms