Skip to content

Commit

Permalink
Fix performance issue when assigning short names to variables
Browse files Browse the repository at this point in the history
  • Loading branch information
vouillon committed Sep 23, 2024
1 parent 4174f52 commit 13128c5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
19 changes: 14 additions & 5 deletions compiler/lib/wasm/wa_wasm_output.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1043,22 +1043,31 @@ end = struct
output_byte ch id;
with_size f ch x

let rec find_available_name used name i =
let nm = Printf.sprintf "%s$%d" name i in
if StringSet.mem nm used then find_available_name used name (i + 1) else nm

let assign_names f tbl =
let names = Hashtbl.fold (fun name idx rem -> (idx, name) :: rem) tbl [] in
let names = List.sort ~cmp:(fun (idx, _) (idx', _) -> compare idx idx') names in
let used = ref StringSet.empty in
let counts = Hashtbl.create 101 in
let rec find_available_name used name =
let i =
try Hashtbl.find counts name
with Not_found ->
let i = ref 0 in
Hashtbl.replace counts name i;
i
in
incr i;
let nm = Printf.sprintf "%s$%d" name !i in
if StringSet.mem nm used then find_available_name used name else nm
in
let names =
List.map
~f:(fun (idx, x) ->
match f x with
| None -> idx, None
| Some nm ->
let nm =
if StringSet.mem nm !used then find_available_name !used nm 1 else nm
if StringSet.mem nm !used then find_available_name !used nm else nm
in
used := StringSet.add nm !used;
idx, Some nm)
Expand Down
17 changes: 13 additions & 4 deletions compiler/lib/wasm/wa_wat_output.ml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,18 @@ let target = `Binaryen (*`Reference*)

let assign_names ?(reversed = true) f names =
let used = ref StringSet.empty in
let rec find_available_name used name i =
let nm = Printf.sprintf "%s$%d" name i in
if StringSet.mem nm used then find_available_name used name (i + 1) else nm
let counts = Hashtbl.create 101 in
let rec find_available_name used name =
let i =
try Hashtbl.find counts name
with Not_found ->
let i = ref 0 in
Hashtbl.replace counts name i;
i
in
incr i;
let nm = Printf.sprintf "%s$%d" name !i in
if StringSet.mem nm used then find_available_name used name else nm
in
let names = if reversed then List.rev names else names in
let names =
Expand All @@ -35,7 +44,7 @@ let assign_names ?(reversed = true) f names =
| None -> x, None
| Some nm ->
let nm =
if StringSet.mem nm !used then find_available_name !used nm 1 else nm
if StringSet.mem nm !used then find_available_name !used nm else nm
in
used := StringSet.add nm !used;
x, Some nm)
Expand Down

0 comments on commit 13128c5

Please sign in to comment.