From b18b48099be3bf4d738bd82e36e4212c69176e50 Mon Sep 17 00:00:00 2001 From: Aybek <100071536+zhayt@users.noreply.github.com> Date: Fri, 5 Jul 2024 11:34:02 +0500 Subject: [PATCH] Optimize ColumnNumberToName function performance, reduce about 50% memory usage and 50% time cost (#1935) Co-authored-by: zhayt --- lib.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lib.go b/lib.go index 420f69a..e01c305 100644 --- a/lib.go +++ b/lib.go @@ -232,12 +232,18 @@ func ColumnNumberToName(num int) (string, error) { if num < MinColumns || num > MaxColumns { return "", ErrColumnNumber } - var col string + estimatedLength := 0 + for n := num; n > 0; n = (n - 1) / 26 { + estimatedLength++ + } + + result := make([]byte, estimatedLength) for num > 0 { - col = string(rune((num-1)%26+65)) + col + estimatedLength-- + result[estimatedLength] = byte((num-1)%26 + 'A') num = (num - 1) / 26 } - return col, nil + return string(result), nil } // CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates