Last active
August 26, 2022 20:10
-
-
Save Deleplace/838d23bfdb710fc8b53547360ea6b5f8 to your computer and use it in GitHub Desktop.
Benchmark deleting the parts of a slice, for various slice lengths
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 delete | |
import ( | |
"fmt" | |
"testing" | |
"golang.org/x/exp/slices" | |
) | |
func BenchmarkDeleteLast(b *testing.B) { | |
for k := 10; k < 10_000_000; k *= 10 { | |
name := fmt.Sprintf("DeleteLast_1_%d", k) | |
b.Run(name, func(b *testing.B) { | |
s := make([]byte, k) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
Sink = slices.Delete(s, k-1, k) | |
} | |
}) | |
} | |
} | |
func BenchmarkDeleteLast1000(b *testing.B) { | |
for k := 1000; k < 10_000_000; k *= 10 { | |
name := fmt.Sprintf("DeleteLast_1000_%d", k) | |
b.Run(name, func(b *testing.B) { | |
s := make([]byte, k) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
Sink = slices.Delete(s, k-1, k) | |
} | |
}) | |
} | |
} | |
func BenchmarkDeleteMiddle(b *testing.B) { | |
for k := 10; k < 10_000_000; k *= 10 { | |
name := fmt.Sprintf("DeleteMiddle_1_%d", k) | |
b.Run(name, func(b *testing.B) { | |
s := make([]byte, k) | |
m := k / 2 | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
Sink = slices.Delete(s, m, m+1) | |
} | |
}) | |
} | |
} | |
// Prevent optimizing things away | |
var Sink []byte |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on my workstation:
The first part
DeleteLast
shows that deleting the end of a slice is constant time, regardless the size of the slice, and regardless the number of elements to delete.The second part
DeleteMiddle
is consistent with the amount of work needed to shift half of the slice to the left, which is O(len(s)-j).