From 4d8e1e7cee6fe8321faf21bef907789a502e534a Mon Sep 17 00:00:00 2001 From: FinnTew Date: Sun, 24 Nov 2024 16:59:33 +0800 Subject: [PATCH] optimize: optimize the speed of buildLockKey --- .../undo/builder/basic_undo_log_builder.go | 45 ++++++++++--------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/pkg/datasource/sql/undo/builder/basic_undo_log_builder.go b/pkg/datasource/sql/undo/builder/basic_undo_log_builder.go index a619c15e4..382384445 100644 --- a/pkg/datasource/sql/undo/builder/basic_undo_log_builder.go +++ b/pkg/datasource/sql/undo/builder/basic_undo_log_builder.go @@ -272,35 +272,38 @@ func (b *BasicUndoLogBuilder) buildLockKey(rows driver.Rows, meta types.TableMet // the string as local key. the local key example(multi pk): "t_user:1_a,2_b" func (b *BasicUndoLogBuilder) buildLockKey2(records *types.RecordImage, meta types.TableMeta) string { - var ( - lockKeys bytes.Buffer - filedSequence int - ) + var lockKeys bytes.Buffer lockKeys.WriteString(meta.TableName) lockKeys.WriteString(":") keys := meta.GetPrimaryKeyOnlyName() + keyIndexMap := make(map[string]int, len(keys)) - for _, row := range records.Rows { - if filedSequence > 0 { - lockKeys.WriteString(",") - } - pkSplitIndex := 0 + for idx, columnName := range keys { + keyIndexMap[columnName] = idx + } + + primaryKeyRows := make([][]interface{}, len(records.Rows)) + + for i, row := range records.Rows { + primaryKeyValues := make([]interface{}, len(keys)) for _, column := range row.Columns { - var hasKeyColumn bool - for _, key := range keys { - if column.ColumnName == key { - hasKeyColumn = true - if pkSplitIndex > 0 { - lockKeys.WriteString("_") - } - lockKeys.WriteString(fmt.Sprintf("%v", column.Value)) - pkSplitIndex++ - } + if idx, exist := keyIndexMap[column.ColumnName]; exist { + primaryKeyValues[idx] = column.Value } - if hasKeyColumn { - filedSequence++ + } + primaryKeyRows[i] = primaryKeyValues + } + + for i, primaryKeyValues := range primaryKeyRows { + if i > 0 { + lockKeys.WriteString(",") + } + for j, pkVal := range primaryKeyValues { + if j > 0 { + lockKeys.WriteString("_") } + lockKeys.WriteString(fmt.Sprintf("%v", pkVal)) } }