clib.Session: Refactor the __getitem__
special method to avoid calling API function GMT_Get_Enum repeatedly
#3261
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The
__getitem__
method is a magic method that makes theSession
class behave like a dictionary so that we can access the value of GMT constants likeself["GMT_IS_DATASET"]
.self["GMT_IS_DATSET"]
is translated to the statementself.__get_item__("GMT_IS_DATASET")
, which then calls the GMT C API functionGMT_Get_Enum
.Currently, the
__getitem__
method calls theGMT_Get_Enum
function everytime a constant is accessed, so it's not efficient. To check how many times constants are accessed, I've added a print statement in the__getitem__
method.As you can see, even in the simplest script,
GMT_PAD_DEFAULT
andGMT_SESSION_EXTERNAL
are called 7 times each.This PR refactors the
__getitem__
method by storing the values of GMT constants in theGMT_CONSTANTS
dictionary. When a constant is accessed for the first time,GMT_Get_Enum
is called to the get its value and the value is stored inGMT_CONSTANTS
. When the constant is accessed later, it will get the value from theGMT_CONSTANTS
dictionary directly.Below is a simple benchmark showing the performance improvement.
Main branch:
This branch:
From the benchmark result, we can conclude that:
GMT_CONSTANTS
dictionary takes about 66 ns, which is 10x fasterThis PR doesn't affect our "Benchmarks" workflow, because in our tests,
__get_item__
is usually called a few times (like 10), so the execution time may decrease by only 10 ms, which has minor effects on the "Benchmarks" results.