Skip to content

Commit f6a44ed

Browse files
committed
Use better growth rate formula
1 parent 7ccebcc commit f6a44ed

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

src/vec.ml

+7-9
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ type ('a, -'p) t =
33
; mutable length: int
44
}
55

6-
let growth_rate = 1.5
7-
86
let[@inline] array_uninit n = Array.make n (Obj.magic 0)
97

108
let[@inline] make_unsafe capacity length = { data = array_uninit capacity; length }
@@ -47,16 +45,16 @@ let try_get v i =
4745
let[@inline] try_set v i a = i >= 0 && i < v.length && (v.data.(i) <- a; true)
4846

4947
let reserve c v =
50-
let cap = capacity v in
51-
if c > cap then
52-
let cap = ref (if cap = 0 then growth_rate else float_of_int cap) in
53-
let c = float_of_int c in
48+
let old_c = capacity v in
49+
if c > old_c then
50+
(* Formula taken from ocaml-containers CCVector implementation: https://github.com/c-cube/ocaml-containers/blob/69cd3ca78d60fbcb9aa2e6e63d92015af1f54941/src/core/CCVector.ml#L45 *)
51+
let new_c = ref (old_c + (old_c lsr 1) + 2) in
5452

55-
while !cap < c do
56-
cap := !cap *. growth_rate
53+
while !new_c < c do
54+
new_c := !new_c + (!new_c lsr 1) + 2
5755
done;
5856

59-
let data = array_uninit (int_of_float !cap) in
57+
let data = array_uninit !new_c in
6058
Array.blit v.data 0 data 0 v.length;
6159
v.data <- data
6260

0 commit comments

Comments
 (0)