From f7a909d56b665af7c4a780670d6fac0d1049d146 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 19 Mar 2026 23:54:18 +0100 Subject: [PATCH] cli/command/formatter: optimize ContainerContext.Names Optimize formatting of container name(s); - Inline `StripNamePrefix` in the loop, so that we don't have to construct a new slice with names (in most cases only to pick the first one). - Don't use `strings.Split`, as it allocates a new slice and we only used it to check if the container-name was a legacy-link (contained slashes). - Use a string-builder to concatenate names when not truncating instead of using an intermediate slice (and `strings.Join`). Signed-off-by: Sebastiaan van Stijn --- cli/command/formatter/container.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/cli/command/formatter/container.go b/cli/command/formatter/container.go index 0559364e7e..e17313a6dc 100644 --- a/cli/command/formatter/container.go +++ b/cli/command/formatter/container.go @@ -141,18 +141,28 @@ func (c *ContainerContext) ID() string { // Names returns a comma-separated string of the container's names, with their // slash (/) prefix stripped. Additional names for the container (related to the -// legacy `--link` feature) are omitted. +// legacy `--link` feature) are omitted when formatting "truncated". func (c *ContainerContext) Names() string { - names := StripNamePrefix(c.c.Names) - if c.trunc { - for _, name := range names { - if len(strings.Split(name, "/")) == 1 { - names = []string{name} - break + var b strings.Builder + for i, n := range c.c.Names { + name := strings.TrimPrefix(n, "/") + if c.trunc { + // When printing truncated, we only print a single name. + // + // Pick the first name that's not a legacy link (does not have + // slashes inside the name itself (e.g., "/other-container/link")). + // Normally this would be the first name found. + if strings.IndexByte(name, '/') == -1 { + return name } + continue } + if i > 0 { + b.WriteByte(',') + } + b.WriteString(name) } - return strings.Join(names, ",") + return b.String() } // StripNamePrefix removes any "/" prefix from container names returned