Senior
How did you optimize search scenarios?
sobes.tech AI
Answer from AI
To optimize search scenarios in Go, I employed several approaches:
- Using indexes and data structures suitable for the type of search (e.g., hash tables, B-trees, trigrams).
- Caching results of frequent queries with built-in or third-party caches (e.g., groupcache).
- Parallel processing of requests using goroutines to speed up searches over large data volumes.
- Optimizing database queries: minimizing the number of queries, using prepared statements, proper schema design.
- Profiling code with pprof to identify bottlenecks and eliminate them.
Example of a simple parallel search over a slice of strings:
func parallelSearch(data []string, query string) []string {
var wg sync.WaitGroup
results := make(chan string)
for _, item := range data {
wg.Add(1)
go func(s string) {
defer wg.Done()
if strings.Contains(s, query) {
results <- s
}
}(item)
}
go func() {
wg.Wait()
close(results)
}()
var found []string
for r := range results {
found = append(found, r)
}
return found
}