From 3cdf606183c38c6b7b598bfe76d65604f49d7799 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Fri, 31 Aug 2018 21:20:39 +0200 Subject: [PATCH] Improve runtime.printuint32: avoid recursion This reduces size slightly at least on the PCA10040, and is probably faster and probably uses less stack as well. --- src/runtime/print.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/runtime/print.go b/src/runtime/print.go index fcb09d71..206ffb51 100644 --- a/src/runtime/print.go +++ b/src/runtime/print.go @@ -43,13 +43,21 @@ func printint16(n uint16) { } func printuint32(n uint32) { - // TODO: don't recurse, but still be compact (and don't divide/mod - // more than necessary). - prevdigits := n / 10 - if prevdigits != 0 { - printuint32(prevdigits) + digits := [10]byte{} // enough to hold (2^32)-1 + // Fill in all 10 digits. + firstdigit := 9 // digit index that isn't zero (by default, the last to handle '0' correctly) + for i := 9; i >= 0; i-- { + digit := byte(n%10 + '0') + digits[i] = digit + if digit != '0' { + firstdigit = i + } + n /= 10 + } + // Print digits without the leading zeroes. + for i := firstdigit; i < 10; i++ { + putchar(digits[i]) } - putchar(byte((n % 10) + '0')) } func printint32(n int32) {