From 563ae74a197534aa2a9f15c144e5a8f55d84bdf7 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Sun, 16 Jun 2024 00:21:53 +0800 Subject: [PATCH] some optimize --- include/pocketpy/common/algorithm.h | 2 +- include/pocketpy/xmacros/smallmap.h | 21 ++++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/include/pocketpy/common/algorithm.h b/include/pocketpy/common/algorithm.h index a3ce50b8..92a09328 100644 --- a/include/pocketpy/common/algorithm.h +++ b/include/pocketpy/common/algorithm.h @@ -13,7 +13,7 @@ extern "C" { T* __first = ptr; \ int __len = count; \ while(__len != 0) { \ - int __l2 = (int)((unsigned int)__len / 2); \ + int __l2 = __len >> 1; \ T* __m = __first + __l2; \ if(less((*__m), (key))) { \ __first = ++__m; \ diff --git a/include/pocketpy/xmacros/smallmap.h b/include/pocketpy/xmacros/smallmap.h index 8422d09b..173f8966 100644 --- a/include/pocketpy/xmacros/smallmap.h +++ b/include/pocketpy/xmacros/smallmap.h @@ -64,14 +64,21 @@ void SMALLMAP_METHOD(set)(SMALLMAP* self, K key, V value) { } V* SMALLMAP_METHOD(try_get)(const SMALLMAP* self, K key) { - int index; - c11__lower_bound(KV, self->data, self->count, key, less, &index); - KV* it = c11__at(KV, self, index); - if(index != self->count && equal(it->key, key)) { - return &it->value; - } else { - return NULL; + // use `bsearch` which is faster than `lower_bound` + int low = 0; + int high = self->count - 1; + KV* a = self->data; + while(low <= high){ + int mid = (low + high) / 2; + if(equal(a[mid].key, key)){ + return &a[mid].value; + } else if(less(a[mid], key)){ + low = mid + 1; + } else { + high = mid - 1; + } } + return NULL; } V SMALLMAP_METHOD(get)(const SMALLMAP* self, K key, V default_value) {