Do not modify input in-place

SortedUniqueStrings and FirstUniqueStrings dedupes repeating elements
and returns the deduped list. Currently, it also modifies the input list
in-place, which causes non-determinisitc failures like b/275313114

Operate on a copy of the input so that the input remains untouched.

SortedUniqueStrings is O(NlogN) and FirstUniqueStrings is ~O(N), so
creating a copy (O(N)) should not result in major performance regressions.
Numbers for this single unit test:
```
go test . -run TestStubsForLibraryInMultipleApexes -v -count 1000
Before: 174s
After: 172s
```

Bug: 275313114
Test: go test ./android
Test: go test . -run TestStubsForLibraryInMultipleApexes -v -count 1000
(cherry picked from https://android-review.googlesource.com/q/commit:8a8714c781175f8f1a6c189d919ee8b0ee8c1e27)
Merged-In: Id859723b2c2ebdc0023876c4b6fabe75d870bad7
Change-Id: Id859723b2c2ebdc0023876c4b6fabe75d870bad7
This commit is contained in:
Spandan Das
2023-04-25 18:03:54 +00:00
committed by Yu Liu
parent dabeb50e32
commit ee84727d95

View File

@@ -276,6 +276,8 @@ func RemoveFromList(s string, list []string) (bool, []string) {
// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
// each. It modifies the slice contents in place, and returns a subslice of the original slice.
func FirstUniqueStrings(list []string) []string {
// Do not moodify the input in-place, operate on a copy instead.
list = CopyOf(list)
// 128 was chosen based on BenchmarkFirstUniqueStrings results.
if len(list) > 128 {
return firstUniqueStringsMap(list)
@@ -332,6 +334,7 @@ func LastUniqueStrings(list []string) []string {
// SortedUniqueStrings returns what the name says
func SortedUniqueStrings(list []string) []string {
// FirstUniqueStrings creates a copy of `list`, so the input remains untouched.
unique := FirstUniqueStrings(list)
sort.Strings(unique)
return unique