Advanced Slice Techniques
Slice Manipulation Techniques
1. Efficient Slice Filtering
// Filter even numbers
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
filteredNumbers := []int{}
for _, num := range numbers {
if num%2 == 0 {
filteredNumbers = append(filteredNumbers, num)
}
}
// Transform slice using map
original := []int{1, 2, 3, 4, 5}
squared := make([]int, len(original))
for i, num := range original {
squared[i] = num * num
}
Memory Management Strategies
graph TD
A[Slice Memory Management] --> B[Preallocate]
A --> C[Minimize Reallocations]
A --> D[Use Copy Instead of Append]
Slice Memory Optimization
// Efficient slice copying
source := []int{1, 2, 3, 4, 5}
destination := make([]int, len(source))
copy(destination, source)
Advanced Slice Operations
Slice as Function Parameters
// Slice mutation function
func modifySlice(s []int) {
for i := range s {
s[i] *= 2
}
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
modifySlice(numbers)
// numbers is modified in-place
}
Technique |
Description |
Performance Impact |
Preallocate |
Use make() with capacity |
Reduces memory reallocation |
Copy |
Use copy() instead of append |
More efficient for large slices |
In-place Modification |
Modify slice directly |
Avoids unnecessary allocations |
Slice Capacity Management
// Efficient slice growth
func growSlice(s []int, newSize int) []int {
if cap(s) < newSize {
// Create new slice with increased capacity
newSlice := make([]int, len(s), newSize)
copy(newSlice, s)
return newSlice
}
return s
}
Advanced Slice Patterns
1. Slice Chunking
func chunkSlice(slice []int, chunkSize int) [][]int {
var chunks [][]int
for i := 0; i < len(slice); i += chunkSize {
end := i + chunkSize
if end > len(slice) {
end = len(slice)
}
chunks = append(chunks, slice[i:end])
}
return chunks
}
2. Slice Deduplication
func removeDuplicates(slice []int) []int {
seen := make(map[int]bool)
result := []int{}
for _, val := range slice {
if !seen[val] {
seen[val] = true
result = append(result, val)
}
}
return result
}
graph LR
A[Slice Performance] --> B[Minimize Allocations]
A --> C[Use Appropriate Data Structures]
A --> D[Benchmark and Profile]
LabEx Recommendation
When working with advanced slice techniques:
- Always consider memory efficiency
- Profile your code for performance bottlenecks
- Choose the right technique for your specific use case
By mastering these advanced slice techniques, you'll write more efficient and elegant Go code.