How Do I Compare Strings in Go?
Last Update: Jun 7, 2024
I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.
So you’re just learning Go and how things work. You need to compare two strings to see if they’re equal. You want to do it as simply and quickly as possible.
In this tutorial we’re going to learn:
- Different ways to compare Strings
- Comparing strings ignoring case
- Measuring performance of different methods.
So let’s get started.
Note: There’s a video version of this article as well.
Basic String Comparison
So you need to compare a string. You can use comparison operators:
sampleString := "This is a sample string"
compareString := "this is a sample string"
if sampleString == compareString {
println("The strings match")
}else {
println("Strings do not match")
}
This is relatively quick and easy.
You can also use the Strings package to achieve the same thing:
if strings.Compare(sampleString, compareString) == 0 {
println("The strings match")
}else {
println("Strings do not match")
}
Here is our result:
Both will do a straightforward comparison, and both will compare by lexicographic order: alphabetic order, except uppercase letters come before lowercase.
Case Insensitive String Comparison
The previous examples are case sensitive compares. You may be looking to see if a particular phrase is the same, regardless of how it’s capitalized.
If you want to compare the string content, and ignore whether letters are upper or lowercase:
Comparison Operators:
if strings.ToLower(sampleString) == strings.ToLower(compareString) {
println("The strings match")
}else {
println("Strings do not match")
}
Compare from Strings Package:
if strings.Compare(strings.ToLower(sampleString), strings.ToLower(compareString)) == 0 {
println("The strings match")
}else {
println("Strings do not match")
}
This is a great way to compare the exact content of the string. This is how I make string comparisons most of the time.
Since the only difference between our strings is capitalization, we see this:
There’s yet another way to do case insensitive comparisons, that’s even faster.
Using EqualFold for Comparisons
The Strings package has a neat function named EqualFold:
if strings.EqualFold(sampleString, compareString) {
println("The strings match")
}else {
println("Strings do not match")
}
Using EqualFold you get a function that normalizes the string with Unicode case-folding. This is a cleaner way of doing what we did above. It compares the string content while ignoring the case.
So now you have a few ways to compare strings. One uses comparison operators, and the other uses elements of the Strings package.
So if we can use comparison operators, why bother with the Strings package?
Which way is faster? Will it scale? What if we have a million people a day using our application?
Which Method Is the Fastest?
Let’s see which method is the fastest. So I generated some fake data with Mockaroo, and it’s a list of names, one per line. Let’s parse through this list to find a match.
Boy howdy, that’s 200,000 strings to compare. At the end of the file I added “1234” to the end of it to make sure it’s unique, and we’d have to parse the whole file to find a match.
So, let’s put together something to perform a search against every name in the file.
Reading the File
For this task, I’ll use a Bufio Scanner to read the file. The new Go application looks like this:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("names.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
compareString := scanner.Text()
fmt.Printf("%s\n", compareString)
}
file.Close()
}
So running this application against 200k lines is the same as the cat command in Linux/Unix:
It takes around 8 seconds to process the file. If we run string comparisons on each line, we should see a difference in the functions’ speed.
Let’s create functions for each of our comparison methods, and time them.
Creating Functions and Timing the Application
The first one we try out is a function using comparison operators;
func compareOperators(a string, b string) bool {
// compare with operators
if a == b {
return true
}
return false
}
so now our main looks like this:
func main() {
sampleString := "Immanuel1234"
file, err := os.Open("names.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
if compareOperators(sampleString, scanner.Text()) {
fmt.Printf("We found a match!")
}
}
file.Close()
}
Let’s run it:
Wow. .225 seconds, pretty fast.
Let’s try the function that uses the Strings package.
func compareString(a string, b string) bool {
if strings.Compare(a, b) == 0 {
return true
}
return false
}
Let’s run it:
Hmm, .138 seconds. Even faster.
This seems a bit off. Just to be sure, let’s get a better sample. I’ll run each five times and get an average speed.
The average speed for comparison operators is .1668 seconds.
The average speed for the Strings package compare is .1394 seconds.
An interesting gap indeed. It appears that Strings package comparisons are slightly faster.
Experimenting with Case Insensitive Comparisons
Next, let’s run some case insensitive tests.
Comparison Operators:
func compareOperators(a string, b string) bool {
// compare with operators
if strings.ToLower(a) == strings.ToLower(b) {
return true
}
return false
}
Average Time: .1700 seconds.
Strings Package
func compareString(a string, b string) bool {
if strings.Compare(strings.ToLower(a), strings.ToLower(b)) == 0 {
return true
}
return false
}
Average Time: .1598 seconds.
EqualFold
func compareEF(a string, b string) bool {
if strings.EqualFold(a, b) {
return true
}
return false
}
Average Time: .1448 seconds. (Winner)
So Which Is the Fastest?
I don’t like the margins here. It’s a bit too close to call. But it appears that EqualFold compare is the fastest. If you want to do case sensitive compares, this is probably the choice for you.
As with all benchmarks, take these results with a grain of salt. Always perform your own testing if you’re concerned about performance. In a future article, I’m going to do more extensive testing and see what we can come up with.
You can download the files I used for this article here if you want to expand on it.
Summary
So now you know a few different ways to compare a string with Go. You can compare strings and build logic around it. And you have a reasonable idea of which methods are the fastest.
If you want to compare two strings you can use:
- Comparison Operators (Simple)
- Strings.Compare (Faster)
- Strings.EqualFold (Fastest when )
I would advise looking to the Strings package method only because you’ll be using the Strings package in other places.
I cover the Strings package in my course The Go Standard Library and show how to leverage the Strings package to make your string handling duties much easier.
Go build some cool stuff!! Let me know what you think of this and other tutorials.
Want to become an expert Go programmer?
You can boost your skills in a few weekends by taking these high quality Go courses taught by top experts!
We have over 30 hours of Go courses you can take now! You can try it for 10 days free of charge.