Skip to content

Commit 2f139bc

Browse files
committed
nat: ParsePortSpec: prevent repeated parsing
This function constructs port-ranges, and validates the protocol. Calling `NewPort` in a loop means it was parsing the port-spec multiple times. While at it, also pre-allocate the slice that's used, making it ~28% faster, ~26% fewer allocations, and ~15% less memory. Before/after: BenchmarkParsePortSpecs-10 73500 15198 ns/op 18248 B/op 359 allocs/op BenchmarkParsePortSpecs-10 105000 10925 ns/op 15520 B/op 264 allocs/op Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent a5f5cb3 commit 2f139bc

1 file changed

Lines changed: 7 additions & 10 deletions

File tree

nat/nat.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
198198
return nil, errors.New("invalid containerPort: " + containerPort)
199199
}
200200

201-
var startHostPort, endHostPort uint64 = 0, 0
201+
var startHostPort, endHostPort uint64
202202
if hostPort != "" {
203203
startHostPort, endHostPort, err = ParsePortRange(hostPort)
204204
if err != nil {
@@ -215,9 +215,11 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
215215
}
216216
}
217217

218-
ports := []PortMapping{}
219-
for i := uint64(0); i <= (endPort - startPort); i++ {
220-
cPort := strconv.FormatUint(startPort+i, 10)
218+
count := endPort - startPort + 1
219+
ports := make([]PortMapping, 0, count)
220+
221+
for i := uint64(0); i < count; i++ {
222+
cPort := Port(strconv.FormatUint(startPort+i, 10) + "/" + proto)
221223
hPort := ""
222224
if hostPort != "" {
223225
hPort = strconv.FormatUint(startHostPort+i, 10)
@@ -227,13 +229,8 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
227229
if startPort == endPort && startHostPort != endHostPort {
228230
hPort += "-" + strconv.FormatUint(endHostPort, 10)
229231
}
230-
port, err := NewPort(proto, cPort)
231-
if err != nil {
232-
return nil, err
233-
}
234-
235232
ports = append(ports, PortMapping{
236-
Port: port,
233+
Port: cPort,
237234
Binding: PortBinding{HostIP: ip, HostPort: hPort},
238235
})
239236
}

0 commit comments

Comments
 (0)