Created
February 11, 2022 15:47
-
-
Save jameinel/22fc619d8b69459c1be83481180d2a71 to your computer and use it in GitHub Desktop.
Benchmark copy vs append
This file contains 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 foo | |
import "testing" | |
func createSource(b *testing.B) []int { | |
source := make([]int, b.N) | |
for i := range source { | |
source[i] = i | |
} | |
b.ResetTimer() | |
return source | |
} | |
func BenchmarkCopyN(b *testing.B) { | |
source := createSource(b) | |
dest := make([]int, len(source)) | |
copy(dest, source) | |
} | |
func BenchmarkAppendN(b *testing.B) { | |
source := createSource(b) | |
dest := append([]int(nil), source...) | |
_ = dest | |
} | |
func BenchmarkAppendSourceN(b *testing.B) { | |
source := createSource(b) | |
dest := append(source[:0], source...) | |
_ = dest | |
} | |
func createN(b *testing.B, n int) []int { | |
source := make([]int, n) | |
for i := range source { | |
source[i] = i | |
} | |
b.ResetTimer() | |
return source | |
} | |
func BenchmarkCopy1000(b *testing.B) { | |
source := createN(b, 1000) | |
for i := 0; i < b.N; i++ { | |
dest := make([]int, len(source)) | |
copy(dest, source) | |
_ = dest | |
} | |
} | |
func BenchmarkAppend1000(b *testing.B) { | |
source := createN(b, 1000) | |
for i := 0; i < b.N; i++ { | |
dest := append([]int(nil), source...) | |
_ = dest | |
} | |
} | |
func BenchmarkAppendSource1000(b *testing.B) { | |
source := createN(b, 1000) | |
for i := 0; i < b.N; i++ { | |
dest := append(source[:0], source...) | |
_ = dest | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment