From 8e1670cc60cc853c7ddc81dceb65dc93fa45bfa9 Mon Sep 17 00:00:00 2001 From: Dylan Baker Date: Mon, 22 Apr 2019 15:43:03 -0700 Subject: rewriter: optimize the list_to_dict function This uses an iterator instead of walking a list, which is roughly twice as fast. This also does away with the pre-check on whether the list is valid for converting to a dict, and instead handles the case of an uneven number by catching another exception. This is preferable since it's a fatal error anyway, so avoiding it in the non-fatal case is preferable. --- mesonbuild/rewriter.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'mesonbuild/rewriter.py') diff --git a/mesonbuild/rewriter.py b/mesonbuild/rewriter.py index 6205eae..1558cdd 100644 --- a/mesonbuild/rewriter.py +++ b/mesonbuild/rewriter.py @@ -874,11 +874,16 @@ target_operation_map = { } def list_to_dict(in_list: List[str]) -> Dict[str, str]: - if len(in_list) % 2 != 0: - raise TypeError('An even ammount of arguments are required') result = {} - for i in range(0, len(in_list), 2): - result[in_list[i]] = in_list[i + 1] + it = iter(in_list) + try: + for i in it: + # calling next(it) is not a mistake, we're taking the next element from + # the iterator, avoiding te need to preprocess it into a sequence of + # key value pairs. + result[i] = next(it) + except StopIteration: + raise TypeError('in_list parameter of list_to_dict must have an even length.') return result def generate_target(options) -> List[dict]: -- cgit v1.1