Skip to content

Commit 3679a47

Browse files
dlechdpgeorge
authored andcommitted
py/runtime: Do not overallocate when len is known.
This fixes overallocating an extra mp_obj_t when the length of *args and **args is known. Previously we were allocating 1 mp_obj_t for each n_args and n_kw plus the length of each *arg and **arg (if they are known). Since n_args includes *args and n_kw includes **args, this was allocating an extra mp_obj_t in addition to the length of these args when unpacked. To fix this, we just subtract 1 from the length to account for the 1 already implicitly allocated by n_args and n_kw. Signed-off-by: David Lechner <david@pybricks.com>
1 parent 783b1a8 commit 3679a47

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

py/runtime.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -715,27 +715,29 @@ void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_
715715
uint args2_len = 0;
716716

717717
// Try to get a hint for unpacked * args length
718-
uint list_len = 0;
718+
int list_len = 0;
719719

720720
if (star_args != 0) {
721721
for (uint i = 0; i < n_args; i++) {
722722
if (star_args & (1 << i)) {
723723
mp_obj_t len = mp_obj_len_maybe(args[i]);
724724
if (len != MP_OBJ_NULL) {
725-
list_len += mp_obj_get_int(len);
725+
// -1 accounts for 1 of n_args occupied by this arg
726+
list_len += mp_obj_get_int(len) - 1;
726727
}
727728
}
728729
}
729730
}
730731

731732
// Try to get a hint for the size of the kw_dict
732-
uint kw_dict_len = 0;
733+
int kw_dict_len = 0;
733734

734735
for (uint i = 0; i < n_kw; i++) {
735736
mp_obj_t key = args[n_args + i * 2];
736737
mp_obj_t value = args[n_args + i * 2 + 1];
737738
if (key == MP_OBJ_NULL && value != MP_OBJ_NULL && mp_obj_is_type(value, &mp_type_dict)) {
738-
kw_dict_len += mp_obj_dict_len(value);
739+
// -1 accounts for 1 of n_kw occupied by this arg
740+
kw_dict_len += mp_obj_dict_len(value) - 1;
739741
}
740742
}
741743

0 commit comments

Comments
 (0)