fix: Avoid slices.Contains within tight loops
Having a `slices.Contains` check within a `for` loop has a complexity of `O(n*m)`, with a worst case scenario of `O(n^2)` for when both collections have the same size. This is because `slices.Contains` internally runs just a regular loop, checking for equality element by element. Instead, this diff changes every occurence of this pattern to converting the collection we compare against to a set, and then running a faster lookup against it.
This commit is contained in:
@@ -98,8 +98,9 @@ func ReorderTracks(tracks []*mediaprovider.Track, idxToMove []int, op TrackReord
|
||||
case MoveToTop:
|
||||
topIdx := 0
|
||||
botIdx := len(idxToMove)
|
||||
idxToMoveSet := ToSet(idxToMove)
|
||||
for i, t := range tracks {
|
||||
if slices.Contains(idxToMove, i) {
|
||||
if _, ok := idxToMoveSet[i]; ok {
|
||||
newTracks[topIdx] = t
|
||||
topIdx++
|
||||
} else {
|
||||
@@ -110,8 +111,9 @@ func ReorderTracks(tracks []*mediaprovider.Track, idxToMove []int, op TrackReord
|
||||
case MoveToBottom:
|
||||
topIdx := 0
|
||||
botIdx := len(tracks) - len(idxToMove)
|
||||
idxToMoveSet := ToSet(idxToMove)
|
||||
for i, t := range tracks {
|
||||
if slices.Contains(idxToMove, i) {
|
||||
if _, ok := idxToMoveSet[i]; ok {
|
||||
newTracks[botIdx] = t
|
||||
botIdx++
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user