@@ -606,6 +606,7 @@ where
606606 // The expression does not exist yet, so we need to create a new group and new expression.
607607 let group = group:: ActiveModel {
608608 status : Set ( 0 ) , // `GroupStatus::InProgress` status.
609+ set_size : Set ( 1 ) ,
609610 ..Default :: default ( )
610611 } ;
611612
@@ -676,18 +677,24 @@ where
676677 left_group_id : GroupId ,
677678 right_group_id : GroupId ,
678679 ) -> OptimizerResult < GroupId > {
679- // Without a rank / size field, we have no way of determining which set is better to merge
680- // into the other. So we will arbitrarily choose to merge the left group into the right
681- // group here. If rank is added in the future, then merge the smaller set into the larger.
680+ let mut left_root_id = self . get_root_group ( left_group_id) . await ?;
681+ let mut left_root = self . get_group ( left_root_id) . await ?;
682+ let mut left_size = left_root. set_size ;
683+
684+ let mut right_root_id = self . get_root_group ( right_group_id) . await ?;
685+ let mut right_root = self . get_group ( right_root_id) . await ?;
686+ let mut right_size = left_root. set_size ;
687+
688+ // Rank/size optimization: merge the smaller set into the larger set.
689+ if left_size > right_size {
690+ std:: mem:: swap ( & mut left_root_id, & mut right_root_id) ;
691+ std:: mem:: swap ( & mut left_root, & mut right_root) ;
692+ std:: mem:: swap ( & mut left_size, & mut right_size) ;
693+ }
682694
683- let left_root_id = self . get_root_group ( left_group_id) . await ?;
684- let left_root = self . get_group ( left_root_id) . await ?;
685695 // A `None` next pointer means it should technically be pointing to itself.
686696 let left_next = left_root. next_id . unwrap_or ( left_root_id. 0 ) ;
687697 let mut active_left_root = left_root. into_active_model ( ) ;
688-
689- let right_root_id = self . get_root_group ( right_group_id) . await ?;
690- let right_root = self . get_group ( right_root_id) . await ?;
691698 // A `None` next pointer means it should technically be pointing to itself.
692699 let right_next = right_root. next_id . unwrap_or ( right_root_id. 0 ) ;
693700 let mut active_right_root = right_root. into_active_model ( ) ;
0 commit comments