From 2c4f731c27ecd4e0f5ba7dd16960c7486a33b046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Ferreira?= Date: Tue, 27 Oct 2020 15:01:29 +0000 Subject: [PATCH] stdio: optimize readln algorithm for non-char type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Instead of using buf.length = 0, use buf = buf[0..0] slice technique to clean the array and reuse, if possible, the buffer to reduce GC allocations. Signed-off-by: Luís Ferreira --- std/stdio.d | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/std/stdio.d b/std/stdio.d index c41469a393b..ae262be6e7e 100644 --- a/std/stdio.d +++ b/std/stdio.d @@ -1846,14 +1846,19 @@ is recommended if you want to process a complete file. } else { - // TODO: optimize this string s = readln(terminator); - buf.length = 0; - if (!s.length) return 0; - foreach (C c; s) + if (!s.length) { - buf ~= c; + buf = buf[0 .. 0]; + return 0; } + + import std.utf : codeLength; + buf.length = codeLength!C(s); + size_t idx; + foreach (C c; s) + buf[idx++] = c; + return buf.length; } }