Select data structures and algorithms based on performance characteristics and actual usage patterns rather than convenience or familiarity. Consider memory efficiency, computational complexity, and scaling behavior when making implementation choices.
Select data structures and algorithms based on performance characteristics and actual usage patterns rather than convenience or familiarity. Consider memory efficiency, computational complexity, and scaling behavior when making implementation choices.
Key principles:
map[T]bool
instead of map[T]T
for sets, since sizeof(bool) < sizeof(T)
for most types)Example of efficient set implementation:
// Inefficient - stores redundant data
struct BadSet[T] {
mut:
main_set map[T]T
}
// Efficient - minimal memory usage
struct GoodSet[T] {
mut:
main_set map[T]bool
}
fn (g GoodSet[T]) elements() []T {
return g.main_set.keys() // Use builtin method instead of manual iteration
}
Example of algorithm selection for duplicate removal:
// Inefficient for large datasets - O(n²) complexity
fn remove_duplicates_slow[T](arr []T) []T {
mut results := []T{}
for val in arr {
if val !in results { // Linear search each time
results << val
}
}
return results
}
// Efficient - O(n) complexity
fn remove_duplicates_fast[T](arr []T) []T {
mut seen := map[T]bool{}
mut results := []T{}
for val in arr {
if !seen[val] {
seen[val] = true
results << val
}
}
return results
}
Enter the URL of a public GitHub repository