Skip to content

Commit

Permalink
Compute small nim string lit at CT (nim-lang#20439)
Browse files Browse the repository at this point in the history
* Reduces runtime overhead for small strings.
* Avoids including `makeNimstrLit` in the output when all strings are
  small enough.
  • Loading branch information
AmjadHD authored and capocasa committed Mar 31, 2023
1 parent 81ce464 commit adcb79f
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions compiler/jsgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit adcb79f

Please sign in to comment.