Skip to content

Commit

Permalink
IH-553: Optimize Sexpr.escape
Browse files Browse the repository at this point in the history
It was allocating a string for each character, only to then immediately add it to a buffer.
Instead add the character to the buffer directly.

The temporary string was probably created to factor out 'Buffer.add',
but I'd rather copy Buffer.add 4x times than have the perf hit.

Further optimizations might be possible here as the comments says,
but this is a low-risk, obvious optimization.

Signed-off-by: Edwin Török <edwin.torok@cloud.com>
  • Loading branch information
edwintorok committed Apr 19, 2024
1 parent e2b0a40 commit 6a0142f
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions ocaml/libs/sexpr/sExpr.ml
Expand Up @@ -39,18 +39,15 @@ let escape s =
let escaped = Buffer.create (String.length s + 10) in
String.iter
(fun c ->
let c' =
match c with
| '\\' ->
"\\\\"
| '"' ->
"\\\""
| '\'' ->
"\\\'"
| _ ->
Astring.String.of_char c
in
Buffer.add_string escaped c'
match c with
| '\\' ->
Buffer.add_string escaped "\\\\"
| '"' ->
Buffer.add_string escaped "\\\""
| '\'' ->
Buffer.add_string escaped "\\\'"
| _ ->
Buffer.add_char escaped c
)
s ;
Buffer.contents escaped
Expand Down

0 comments on commit 6a0142f

Please sign in to comment.