From d755c02b02011b06ba8584a645c2c71cfc746987 Mon Sep 17 00:00:00 2001 From: Amjad Ben Hedhili Date: Tue, 27 Sep 2022 10:11:09 +0100 Subject: [PATCH] Compute small nim string lit at CT (#20439) * Reduces runtime overhead for small strings. * Avoids including `makeNimstrLit` in the output when all strings are small enough. --- compiler/jsgen.nim | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 1a37ab7cf7..cf2a570e36 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -290,6 +290,21 @@ proc makeJSString(s: string, escapeNonAscii = true): Rope = else: result = escapeJSString(s).rope +proc makeJsNimStrLit(s: string): Rope = + var x = newStringOfCap(4*s.len+1) + x.add "[" + var i = 0 + if i < s.len: + x.addInt int64(s[i]) + inc i + while i < s.len: + x.add "," + x.addInt int64(s[i]) + inc i + x.add "]" + result = rope(x) + + include jstypes proc gen(p: PProc, n: PNode, r: var TCompRes) @@ -2605,11 +2620,11 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) = r.kind = resExpr of nkStrLit..nkTripleStrLit: if skipTypes(n.typ, abstractVarRange).kind == tyString: - if n.strVal.len != 0: + if n.strVal.len <= 64: + r.res = makeJsNimStrLit(n.strVal) + else: useMagic(p, "makeNimstrLit") r.res = "makeNimstrLit($1)" % [makeJSString(n.strVal)] - else: - r.res = rope"[]" else: r.res = makeJSString(n.strVal, false) r.kind = resExpr