Skip to content

Commit f7a909d

Browse files
committed
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 <github@gone.nl>
1 parent 2cc9fe1 commit f7a909d

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

cli/command/formatter/container.go

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -141,18 +141,28 @@ func (c *ContainerContext) ID() string {
141141

142142
// Names returns a comma-separated string of the container's names, with their
143143
// slash (/) prefix stripped. Additional names for the container (related to the
144-
// legacy `--link` feature) are omitted.
144+
// legacy `--link` feature) are omitted when formatting "truncated".
145145
func (c *ContainerContext) Names() string {
146-
names := StripNamePrefix(c.c.Names)
147-
if c.trunc {
148-
for _, name := range names {
149-
if len(strings.Split(name, "/")) == 1 {
150-
names = []string{name}
151-
break
146+
var b strings.Builder
147+
for i, n := range c.c.Names {
148+
name := strings.TrimPrefix(n, "/")
149+
if c.trunc {
150+
// When printing truncated, we only print a single name.
151+
//
152+
// Pick the first name that's not a legacy link (does not have
153+
// slashes inside the name itself (e.g., "/other-container/link")).
154+
// Normally this would be the first name found.
155+
if strings.IndexByte(name, '/') == -1 {
156+
return name
152157
}
158+
continue
159+
}
160+
if i > 0 {
161+
b.WriteByte(',')
153162
}
163+
b.WriteString(name)
154164
}
155-
return strings.Join(names, ",")
165+
return b.String()
156166
}
157167

158168
// StripNamePrefix removes any "/" prefix from container names returned

0 commit comments

Comments
 (0)