From b520f4bd1cd151c1c5d769e6237ac9d10297cb7f Mon Sep 17 00:00:00 2001 From: Pavel Hrechyshkin Date: Mon, 22 Feb 2016 01:09:56 +0300 Subject: [PATCH] Issue-860. Preload performance --- preload.go | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/preload.go b/preload.go index a855f794..e1ca69ff 100644 --- a/preload.go +++ b/preload.go @@ -150,20 +150,24 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{}) resultValues := reflect.Indirect(reflect.ValueOf(results)) if scope.IndirectValue().Kind() == reflect.Slice { + preloadMap := make(map[string][]reflect.Value) for i := 0; i < resultValues.Len(); i++ { result := resultValues.Index(i) value := getRealValue(result, relation.ForeignFieldNames) - objects := scope.IndirectValue() - for j := 0; j < objects.Len(); j++ { - object := reflect.Indirect(objects.Index(j)) - if equalAsString(getRealValue(object, relation.AssociationForeignFieldNames), value) { - if object.Kind() == reflect.Ptr { - object = object.Elem() - } - f := object.FieldByName(field.Name) - f.Set(reflect.Append(f, result)) - break + preloadMap[toString(value)] = append(preloadMap[toString(value)], result) + } + + objects := scope.IndirectValue() + for j := 0; j < objects.Len(); j++ { + object := reflect.Indirect(objects.Index(j)) + objectRealValue := getRealValue(object, relation.AssociationForeignFieldNames) + objectStringValue := toString(objectRealValue) + if results, ok := preloadMap[objectStringValue]; ok { + if object.Kind() == reflect.Ptr { + object = object.Elem() } + f := object.FieldByName(field.Name) + f.Set(reflect.Append(f, results...)) } } } else {