summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorlit <litlighilit@foxmail.com>2024-07-02 02:47:08 +0800
committerGitHub <noreply@github.com>2024-07-01 20:47:08 +0200
commita557e5a341edcba90a08b6bc07d1dd701ed29c81 (patch)
treebcab7c799362b9b66f6f83d6166632094e48d74a /lib
parent27abcdd57f43fa905153f38afc7b10b990d789c9 (diff)
downloadNim-a557e5a341edcba90a08b6bc07d1dd701ed29c81.tar.gz
refine: strmisc.expandTabs better code structure (#23783)
After this pr, for a string with just 20 length and 6 `'\t'`, the time reduces by about 1.5%[^t].

Also, the code is clearer than the previous at some places.


[^t]: Generally speaking, this rate increases with length. I may test
for longer string later.
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/strmisc.nim15
1 files changed, 6 insertions, 9 deletions
diff --git a/lib/pure/strmisc.nim b/lib/pure/strmisc.nim
index c8cd839be..a3e539e7e 100644
--- a/lib/pure/strmisc.nim
+++ b/lib/pure/strmisc.nim
@@ -27,20 +27,17 @@ func expandTabs*(s: string, tabSize: int = 8): string =
     doAssert expandTabs("a\tb\n\txy\t", 3) == "a  b\n   xy "
 
   result = newStringOfCap(s.len + s.len shr 2)
-  var pos = 0
 
   template addSpaces(n) =
-    for j in 0 ..< n:
+    for _ in 1..n:
       result.add(' ')
-      pos += 1
+    pos += n
 
-  for i in 0 ..< len(s):
-    let c = s[i]
+  var pos = 0
+  let denominator = if tabSize > 0: tabSize else: 1
+  for c in s:
     if c == '\t':
-      let
-        denominator = if tabSize > 0: tabSize else: 1
-        numSpaces = tabSize - pos mod denominator
-
+      let numSpaces = tabSize - pos mod denominator
       addSpaces(numSpaces)
     else:
       result.add(c)