Created
September 30, 2022 13:51
-
-
Save tebeka/609047fa7e1d0f66d710a6128bebdacb 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 ( | |
"reflect" | |
"testing" | |
) | |
var ( | |
a1, b1 []int | |
aSize = 1239 | |
bSize = 3938 | |
) | |
func init() { | |
for i := 0; i < aSize; i++ { | |
a1 = append(a1, i) | |
} | |
for i := 0; i < bSize; i++ { | |
b1 = append(b1, i) | |
} | |
} | |
func BenchmarkCopy(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
out := concatCopy(a1, b1) | |
if len(out) != aSize+bSize { | |
b.Fatal(len(out)) | |
} | |
} | |
} | |
func BenchmarkAppend(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
out := concatAppend(a1, b1) | |
if len(out) != aSize+bSize { | |
b.Fatal(len(out)) | |
} | |
} | |
} | |
func concatCopy(a, b []int) []int { | |
out := make([]int, len(a)+len(b)) | |
copy(out, a) | |
copy(out[len(a):], b) | |
return out | |
} | |
func concatAppend(a, b []int) []int { | |
out := make([]int, 0, len(a)+len(b)) | |
out = append(out, a...) | |
out = append(out, b...) | |
return out | |
} | |
func TestCopy(t *testing.T) { | |
a := []int{1, 2, 3} | |
b := []int{4, 5} | |
out := concatCopy(a, b) | |
if !reflect.DeepEqual([]int{1, 2, 3, 4, 5}, out) { | |
t.Fatal(out) | |
} | |
} | |
func TestAppend(t *testing.T) { | |
a := []int{1, 2, 3} | |
b := []int{4, 5} | |
out := concatAppend(a, b) | |
if !reflect.DeepEqual([]int{1, 2, 3, 4, 5}, out) { | |
t.Fatal(out) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment