From bc39b0887bad26e28b9dfae1ec129c96171b7e73 Mon Sep 17 00:00:00 2001 From: donutloop Date: Mon, 3 Jan 2022 13:10:15 +0100 Subject: [PATCH] Filter: remove second loop and indexes slice (#12) Use less memory and cpu resources to filter out elements from the slice. --- slice/slice.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/slice/slice.go b/slice/slice.go index 7911e9e..94fdb69 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -154,18 +154,14 @@ func Filter(slice, function interface{}) interface{} { panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String()) } - var indexes []int + res := reflect.MakeSlice(sv.Type(), 0, 0) for i := 0; i < sv.Len(); i++ { flag := fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0] if flag.Bool() { - indexes = append(indexes, i) + res = reflect.Append(res, sv.Index(i)) } } - res := reflect.MakeSlice(sv.Type(), len(indexes), len(indexes)) - for i := range indexes { - res.Index(i).Set(sv.Index(indexes[i])) - } return res.Interface() }