Skip to content

Commit 0d3e06c

Browse files
committed
go: Reduce memory usage and improve speed of Decode by 26%
Use handwritten version of strings.Map. This avoids having to dynamically allocate and resize the byte slice, and allows the compiler to fully remove memory allocations from the operation. As a result, the time spent in StripCode is almost completely removed.
1 parent 83986da commit 0d3e06c

1 file changed

Lines changed: 12 additions & 11 deletions

File tree

go/olc.go

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -188,18 +188,19 @@ func upper(b byte) byte {
188188
// The code is truncated to the first 15 digits, as Decode won't use more,
189189
// to avoid underflow errors.
190190
func StripCode(code string) string {
191-
code = strings.Map(
192-
func(r rune) rune {
193-
if r == Separator || r == Padding {
194-
return -1
195-
}
196-
return rune(upper(byte(r)))
197-
},
198-
code)
199-
if len(code) > maxCodeLen {
200-
return code[:maxCodeLen]
191+
result := make([]byte, maxCodeLen)
192+
pos := 0
193+
for _, r := range code {
194+
if r == Separator || r == Padding {
195+
continue
196+
}
197+
result[pos] = upper(byte(r))
198+
pos++
199+
if pos >= maxCodeLen {
200+
break
201+
}
201202
}
202-
return code
203+
return string(result[:pos])
203204
}
204205

205206
// Because the OLC codes are an area, they can't start at 180 degrees, because they would then have something > 180 as their upper bound.

0 commit comments

Comments
 (0)