I am practicing at leedcode writing solution in golang and rust. I wrote a solution for this problem https://leetcode.com/problems/letter-combinations-of-a-phone-number/ in golang and in rust
package main
func letterCombinations(digits string) []string {
if len(digits) == 0 {
return []string{}
}
letters := [][]string{
{},
{},
{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"},
{"j", "k", "l"},
{"m", "n", "o"},
{"p", "q", "r", "s"},
{"t", "u", "v"},
{"w", "x", "y", "z"},
}
var gen func(index int, digits string) []string
gen = func(index int, digits string) []string {
result := make([]string, 0)
row := letters[int(digits[index]-'0')]
index++
for _, letter := range row {
if index < len(digits) {
for _, res := range gen(index, digits) {
result = append(result, letter+res)
}
} else {
result = append(result, letter)
}
}
return result
}
return gen(0, digits)
}
func main() {
for i := 0; i < 10000; i++ {
letterCombinations("23456789")
}
}
and this in rust
struct Solution;
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.len() == 0 {
return vec![];
}
let letters: [[char; 5]; 10] = [
[0 as char, '0', '0', '0', '0'],
[0 as char, '0', '0', '0', '0'],
[3 as char, 'a', 'b', 'c', '0'], // 2
[3 as char, 'd', 'e', 'f', '0'], // 3
[3 as char, 'g', 'h', 'i', '0'], // 4
[3 as char, 'j', 'k', 'l', '0'], // 5
[3 as char, 'm', 'n', 'o', '0'], // 6
[4 as char, 'p', 'q', 'r', 's'], // 7
[3 as char, 't', 'u', 'v', '0'], // 8
[4 as char, 'w', 'x', 'y', 'z'], // 9
];
fn gen(index: usize, digits: &str, letters: [[char; 5]; 10]) -> Vec<String> {
let result_capacity = (4 as usize).pow(digits.len() as u32);
let mut result: Vec<String> = Vec::with_capacity(result_capacity);
let iletters = digits.chars().nth(index).unwrap().to_digit(10).unwrap() as usize;
let row = letters[iletters];
let index = index + 1;
for i in 1..= row[0] as usize {
if index < digits.len() {
let res = gen(index, digits, letters);
for j in 0..res.len() {
let mut line = String::with_capacity(res[j].len() + 1);
line.push(row[i]);
line.push_str(&res[j]);
result.push(line);
}
} else {
result.push(row[i].to_string());
}
}
return result;
}
return gen(0, &digits, letters);
}
}
fn main() {
for _i in 0..10000 {
Solution::letter_combinations(String::from("23456789"));
}
}
Where I run each solution through 10 000 iterations. Golang solution takes 60 seconds on my laptop. Rust solution takes 556 seconds which is about 10 times slower. I guess it because golang garbage collector does not return heap memory to OS during program and use pre-allocated memory for each iteration. But rust every call of function letterCombinations() allocates memory from OS and frees it back. So rust slower. Am I correct?