From a7bf174050bf729e8e46361de629aaf498c1d38a Mon Sep 17 00:00:00 2001 From: BobTheBuidler <70677534+BobTheBuidler@users.noreply.github.com> Date: Fri, 18 Apr 2025 20:23:06 +0000 Subject: [PATCH 1/2] feat: optimize utility_methods.py This was originally part of my other PR but that is becoming quite cluttered and hard to review so I separated this one out. Previously, the code would create a new dict from `d` one time for each item in the iterable. Now, the code creates just one new dict from `d` at the beginning and uses that same dict to check membership for each item. --- web3/_utils/utility_methods.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/web3/_utils/utility_methods.py b/web3/_utils/utility_methods.py index 66ad373ff2..45051655d8 100644 --- a/web3/_utils/utility_methods.py +++ b/web3/_utils/utility_methods.py @@ -1,7 +1,7 @@ from typing import ( Any, - Dict, Iterable, + Mapping, Set, Union, ) @@ -13,7 +13,7 @@ def all_in_dict( - values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams] + values: Iterable[Any], d: Union[Mapping[Any, Any], TxData, TxParams] ) -> bool: """ Returns a bool based on whether ALL of the provided values exist @@ -24,11 +24,12 @@ def all_in_dict( :return: True if ALL values exist in keys; False if NOT ALL values exist in keys """ - return all(_ in dict(d) for _ in values) + d = dict(d) + return all(_ in d for _ in values) def any_in_dict( - values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams] + values: Iterable[Any], d: Union[Mapping[Any, Any], TxData, TxParams] ) -> bool: """ Returns a bool based on whether ANY of the provided values exist @@ -39,11 +40,12 @@ def any_in_dict( :return: True if ANY value exists in keys; False if NONE of the values exist in keys """ - return any(_ in dict(d) for _ in values) + d = dict(d) + return any(_ in d for _ in values) def none_in_dict( - values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams] + values: Iterable[Any], d: Union[Mapping[Any, Any], TxData, TxParams] ) -> bool: """ Returns a bool based on whether NONE of the provided values exist From 74aa57755a8b14915e7a2c81e87c559675b17b12 Mon Sep 17 00:00:00 2001 From: BobTheBuidler <70677534+BobTheBuidler@users.noreply.github.com> Date: Fri, 18 Apr 2025 20:23:06 +0000 Subject: [PATCH 2/2] chore: add newsfragment --- newsfragments/3667.performance.rst | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 newsfragments/3667.performance.rst diff --git a/newsfragments/3667.performance.rst b/newsfragments/3667.performance.rst new file mode 100644 index 0000000000..eb582f6f1c --- /dev/null +++ b/newsfragments/3667.performance.rst @@ -0,0 +1,4 @@ +Optimize performance for: +web3._utils.utility_methods.all_in_dict +web3._utils.utility_methods.any_in_dict +web3._utils.utility_methods.none_in_dict