Created
March 18, 2025 01:52
-
-
Save Bishwas-py/1a6c9c41bda24e34ffad587dafed1d03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
const iterations = 1000000 // Using a large number to make the difference more noticeable | |
// Measure time for slice without pre-allocated capacity | |
startNoCapacity := time.Now() | |
noCapacity := make([]int, 0) | |
for i := 0; i < iterations; i++ { | |
noCapacity = append(noCapacity, i) | |
} | |
durationNoCapacity := time.Since(startNoCapacity) | |
// Measure time for slice with pre-allocated capacity | |
startWithCapacity := time.Now() | |
withCapacity := make([]int, 0, iterations) | |
for i := 0; i < iterations; i++ { | |
withCapacity = append(withCapacity, i) | |
} | |
durationWithCapacity := time.Since(startWithCapacity) | |
// Print results | |
fmt.Printf("Without capacity: %v\n", durationNoCapacity) | |
fmt.Printf("With capacity: %v\n", durationWithCapacity) | |
fmt.Printf("Performance gain: %.2fx faster\n", float64(durationNoCapacity)/float64(durationWithCapacity)) | |
// Memory usage demonstration (just the length and capacity at the end) | |
fmt.Printf("\nFinal slice stats:\n") | |
fmt.Printf("Without capacity: len=%d cap=%d\n", len(noCapacity), cap(noCapacity)) | |
fmt.Printf("With capacity: len=%d cap=%d\n", len(withCapacity), cap(withCapacity)) | |
} | |
// Without capacity: 18.753703ms | |
// With capacity: 871.065µs | |
// Performance gain: 21.53x faster | |
// Final slice stats: | |
// Without capacity: len=1000000 cap=1055744 | |
// With capacity: len=1000000 cap=1000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment