Skip to content

Commit ba92d7f

Browse files
committed
optimize Sexpr.string_of and Sexpr.escape
Instead of creating lots of buffers for each Sexpr node, create just one toplevel buffer into which everything writes recursively. Signed-off-by: Edwin Török <[email protected]>
1 parent 369a03c commit ba92d7f

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

ocaml/libs/sexpr/sExpr.ml

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,9 @@ let is_escape_char = function '\\' | '"' | '\'' -> true | _ -> false
3232
* - Astring.String.Ascii.escape_string
3333
* - Astring.String.Ascii.unescape
3434
* that have guaranteed invariants and optimised performances *)
35-
let escape s =
35+
let escape_buf escaped s =
3636
let open Astring in
37-
if String.exists is_escape_char s then (
38-
let escaped = Buffer.create (String.length s + 10) in
37+
if String.exists is_escape_char s then
3938
String.iter
4039
(fun c ->
4140
match c with
@@ -48,10 +47,9 @@ let escape s =
4847
| _ ->
4948
Buffer.add_char escaped c
5049
)
51-
s ;
52-
Buffer.contents escaped
53-
) else
54-
s
50+
s
51+
else
52+
Buffer.add_string escaped s
5553

5654
let unescape s =
5755
if String.contains s '\\' then (
@@ -62,8 +60,7 @@ let unescape s =
6260

6361
let mkstring x = String (unescape x)
6462

65-
let string_of sexpr =
66-
let buf = Buffer.create 64 in
63+
let string_of_buf buf sexpr =
6764
let rec __string_of_rec x =
6865
match x with
6966
| Node l ->
@@ -82,7 +79,11 @@ let string_of sexpr =
8279
Buffer.add_char buf ')'
8380
| Symbol s | String s ->
8481
Buffer.add_string buf "\'" ;
85-
Buffer.add_string buf (escape s) ;
82+
escape_buf buf s ;
8683
Buffer.add_string buf "\'"
8784
in
88-
__string_of_rec sexpr ; Buffer.contents buf
85+
__string_of_rec sexpr
86+
87+
let string_of sexpr =
88+
let buf = Buffer.create 64 in
89+
string_of_buf buf sexpr ; Buffer.contents buf

0 commit comments

Comments
 (0)