diff options
author | Stefan Haller <stefan@haller-berlin.de> | 2024-06-23 13:13:58 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-06-23 13:13:58 +0200 |
commit | cf40a5b077343cf6cf3de50b60fc4b47ce929dc1 (patch) | |
tree | b27de3b227276cf54d39238e8162b79eb029567e /pkg/utils/formatting.go | |
parent | a62a5089d6ed5ba989279590a5bd3426829c856d (diff) | |
parent | 26132cf5bdae7ec81e9a0708c722ad2a9cf0c2cf (diff) |
Improve render performance (#3686)
- **PR Description**
Fix a performance regression that I introduced with v0.41: when entering
or leaving staging mode for a file, or when switching from a file that
has only unstaged changes to one that has both staged and unstaged
changes, there was a noticeable lag of about 500ms on my machine. With
the improvements in this PR we get this back down to about 20ms.
Diffstat (limited to 'pkg/utils/formatting.go')
-rw-r--r-- | pkg/utils/formatting.go | 19 |
1 files changed, 16 insertions, 3 deletions
diff --git a/pkg/utils/formatting.go b/pkg/utils/formatting.go index a6bbc5670..b7817346a 100644 --- a/pkg/utils/formatting.go +++ b/pkg/utils/formatting.go @@ -3,6 +3,7 @@ package utils import ( "fmt" "strings" + "unicode" "github.com/mattn/go-runewidth" "github.com/samber/lo" @@ -21,10 +22,22 @@ type ColumnConfig struct { Alignment Alignment } +func StringWidth(s string) int { + // We are intentionally not using a range loop here, because that would + // convert the characters to runes, which is unnecessary work in this case. + for i := 0; i < len(s); i++ { + if s[i] > unicode.MaxASCII { + return runewidth.StringWidth(s) + } + } + + return len(s) +} + // WithPadding pads a string as much as you want func WithPadding(str string, padding int, alignment Alignment) string { uncoloredStr := Decolorise(str) - width := runewidth.StringWidth(uncoloredStr) + width := StringWidth(uncoloredStr) if padding < width { return str } @@ -144,7 +157,7 @@ func getPadWidths(stringArrays [][]string) []int { return MaxFn(stringArrays, func(stringArray []string) int { uncoloredStr := Decolorise(stringArray[i]) - return runewidth.StringWidth(uncoloredStr) + return StringWidth(uncoloredStr) }) }) } @@ -161,7 +174,7 @@ func MaxFn[T any](items []T, fn func(T) int) int { // TruncateWithEllipsis returns a string, truncated to a certain length, with an ellipsis func TruncateWithEllipsis(str string, limit int) string { - if runewidth.StringWidth(str) > limit && limit <= 2 { + if StringWidth(str) > limit && limit <= 2 { return strings.Repeat(".", limit) } return runewidth.Truncate(str, limit, "…") |