I wrote two version programs for string contains test.
The large.txt file opened in code is about 1986163 lines.
the program is aim to read all lines into buffer and then search key words through lines, key_words array/vector have 50 strings in it. The worst case, a string line would execute contains function 50 times.
But the Rust prog executed in about 6s. Go prog executed in about 0.6s.
Why is Go much faster than Rust in this scenario? in fact, it was slowly in excute string contains function.file read is very fast.
Go version:
package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
func check(e error) {
if e != nil {
panic(e)
}
}
var key_words = []string{}
//same with rust version
func contains(line string, words []string) (string, bool) {
for _, word := range words {
if strings.Contains(line, word) {
return word, true
}
}
return "", false
}
func main() {
key_words = append(key_words, "SEARCH LINE FOR TEST BY SATURN")
for i := 0; i < 50; i++ {
s := fmt.Sprintf("SEARCH%d LINE FOR TEST BY SATURN", i)
key_words = append(key_words, s)
}
f, err := os.Open("large.txt")
check(err)
defer f.Close()
scanner := bufio.NewScanner(f)
t0 := time.Now()
for scanner.Scan() {
line := scanner.Text()
if w, ok := contains(line, key_words); ok {
fmt.Println(line, w)
}
}
t1 := time.Now()
fmt.Printf("time: %v", t1.Sub(t0).Seconds())
}
Rust version:
use std::{fs, time::Instant};
fn main() {
let mut key_words = vec![];
key_words.push("SEARCH LINE FOR TEST BY SATURN".to_string());
for i in 1..=50 {
key_words.push(format!("SEARCH{} LINE FOR TEST BY SATURN", i).to_string());
}
// let key_words = vec!["SEARCH LINE FOR TEST BY SATURN","SEARCH LINE FOR TEST BY SATURN2","SEARCH LINE FOR TEST BY SATURN3"];
let contents = fs::read_to_string("large.txt").expect("read failed");
let now = Instant::now();
for line in contents.lines() {
for k in &key_words {
if line.find(k) != None {
println!("{}", line);
break;
}
}
}
println!("{}s", now.elapsed().as_secs_f32())
}