This is an automated email from the ASF dual-hosted git repository.

tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git


The following commit(s) were added to refs/heads/main by this push:
     new f26ff61  perf(container): use iterator lookup instead of exception 
handling in Map/Dict (#548)
f26ff61 is described below

commit f26ff61eea2f7c3c9fe195ebb81873f30b33a81a
Author: Junru Shao <[email protected]>
AuthorDate: Tue Apr 14 04:32:27 2026 -0700

    perf(container): use iterator lookup instead of exception handling in 
Map/Dict (#548)
    
    ## Summary
    
    - Replace `try { n->at(k); } catch (...)` with `n->find(k)` + iterator
    check in `ffi.MapGetItemOrMissing` and `ffi.DictGetItemOrMissing`
    - Avoids the overhead of throwing and catching exceptions on every
    missing-key lookup
    - No behavioral change: both paths return `GetMissingObject()` for
    absent keys
    
    Closes #547
    
    ## Test plan
    
    - [x] `uv run pytest -vvs tests/python` -- 2088 passed, 38 skipped, 3
    xfailed (no new failures)
    - [x] Pre-commit hooks pass (clang-format, ASF header, file types, etc.)
---
 src/ffi/container.cc | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/src/ffi/container.cc b/src/ffi/container.cc
index 6a7c622..cc0b1a1 100644
--- a/src/ffi/container.cc
+++ b/src/ffi/container.cc
@@ -195,11 +195,11 @@ TVM_FFI_STATIC_INIT_BLOCK() {
            })
       .def("ffi.MapGetItemOrMissing",
            [](const ffi::MapObj* n, const Any& k) -> Any {
-             try {
-               return n->at(k);
-             } catch (const tvm::ffi::Error& e) {
-               return GetMissingObject();
+             auto it = n->find(k);
+             if (it != n->end()) {
+               return it->second;
              }
+             return GetMissingObject();
            })
       .def_packed("ffi.Dict",
                   [](ffi::PackedArgs args, Any* ret) {
@@ -227,11 +227,11 @@ TVM_FFI_STATIC_INIT_BLOCK() {
            })
       .def("ffi.DictGetItemOrMissing",
            [](const ffi::DictObj* n, const Any& k) -> Any {
-             try {
-               return n->at(k);
-             } catch (const tvm::ffi::Error& e) {
-               return GetMissingObject();
+             auto it = n->find(k);
+             if (it != n->end()) {
+               return it->second;
              }
+             return GetMissingObject();
            })
       .def("ffi.ContainerFindFirstNonCPUDevice", [](const Any& container) -> 
DLDevice {
         DLDevice result{kDLCPU, 0};

Reply via email to