From 146d58b7af6862aa84bd148a22127eafdb5082c1 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Fri, 23 Oct 2026 17:08:05 -0300 Subject: [PATCH] =?UTF-8?q?Vari=C3=A1veis:=20=C3=ADndice=20hash=20e=20refe?= =?UTF-8?q?r=C3=AAncia=20resolvida=20por=20bloco?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ler uma variável comparava o nome com todas as outras (strcmp linear), e era o que a VM mais fazia: 60% do tempo num render 3D. Agora cada tabela tem um índice hash (a ordem do painel continua a mesma). Além disso, TbVarRef: o bloco resolve o nome uma vez para o slot da variável, preso ao escopo onde foi resolvido; só resolve de novo se uma variável for criada/apagada ou o bloco rodar em outro escopo. "valor de", "mude para" e "mude por" usam a referência. Render do Minecraft em blocos: 86 ms -> 18 ms. Co-Authored-By: Claude Opus 5.5 --- include/tinyblocks/tb_vars.h | 14 +++ .../tinyblocks-variables/src/tb_variables.c | 19 +++- src/tb_vars.c | 103 ++++++++++++++++-- 3 files changed, 123 insertions(+), 13 deletions(-) diff --git a/include/tinyblocks/tb_vars.h b/include/tinyblocks/tb_vars.h index 49d5697..53487b2 100644 --- a/include/tinyblocks/tb_vars.h +++ b/include/tinyblocks/tb_vars.h @@ -12,6 +12,7 @@ #define TINYBLOCKS_TB_VARS_H #include +#include #include typedef struct TbVarScope TbVarScope; @@ -34,6 +35,19 @@ TB_API void tb_vars_declare_global(const char* name, TinyBlocks_Value v); /* apaga a mais interna com esse nome; false se nao existia */ TB_API bool tb_vars_delete(const char* name); +/* -- Acesso rapido (blocos que leem/escrevem sempre a mesma variavel) -- + * O bloco guarda um TbVarRef (zerado no inicio) e o passa a cada chamada: + * o nome e resolvido uma vez para o slot da variavel, preso ao escopo onde + * foi resolvido. So resolve de novo se uma variavel for criada/apagada ou + * se o bloco rodar com outro escopo atual. */ +typedef struct { + uint32_t gen; void* scope; void* table; int idx; + const char* name; + bool fixed; /* quem chama garante: o texto do nome nunca muda (pula o strcmp) */ +} TbVarRef; +TB_API const TinyBlocks_Value* tb_vars_get_ref(const char* name, TbVarRef* ref); +TB_API void tb_vars_set_ref(const char* name, TinyBlocks_Value v, TbVarRef* ref); + /* -- Globais (monitores, salvar projeto) -- */ TB_API int tb_vars_global_count(void); TB_API const char* tb_vars_global_name(int i); diff --git a/libraries/tinyblocks-variables/src/tb_variables.c b/libraries/tinyblocks-variables/src/tb_variables.c index 4659d33..144e2ff 100644 --- a/libraries/tinyblocks-variables/src/tb_variables.c +++ b/libraries/tinyblocks-variables/src/tb_variables.c @@ -18,16 +18,25 @@ #include "tb_variables.h" +/* Cache da variavel no bloco (userdata: liberado com o bloco) */ +static TbVarRef* ref_of(TinyBlocks_Block* self, TinyBlocks* rt) { + if (!self->userdata) { + self->userdata = tb_alloc(rt, sizeof(TbVarRef)); + if (self->userdata) memset(self->userdata, 0, sizeof(TbVarRef)); + } + return (TbVarRef*)self->userdata; +} + static void eval_var_get(TinyBlocks_Block* self, TinyBlocks* rt) { const char* name = tb_block_input_text(self, rt, 0); - const TinyBlocks_Value* v = tb_vars_get(name); + const TinyBlocks_Value* v = tb_vars_get_ref(name, ref_of(self, rt)); tb_block_set_output(self, 0, v ? tb_value_clone(*v) : tb_value_integer(0)); self->dirty = false; } static void eval_var_set(TinyBlocks_Block* self, TinyBlocks* rt) { const char* name = tb_block_input_text(self, rt, 0); - tb_vars_set(name, tb_block_get_input(self, rt, 1)); + tb_vars_set_ref(name, tb_block_get_input(self, rt, 1), ref_of(self, rt)); self->dirty = false; } @@ -39,11 +48,12 @@ static double as_num(const TinyBlocks_Value* v) { static void eval_var_change(TinyBlocks_Block* self, TinyBlocks* rt) { const char* name = tb_block_input_text(self, rt, 0); TinyBlocks_Value by = tb_block_get_input(self, rt, 1); - double a = as_num(tb_vars_get(name)), d = tb_value_as_number(by, 0); + TbVarRef* ref = ref_of(self, rt); + double a = as_num(tb_vars_get_ref(name, ref)), d = tb_value_as_number(by, 0); TinyBlocks_Value nv = (a == floor(a) && d == floor(d)) ? tb_value_integer((long long)llround(a + d)) : tb_value_real(a + d); - tb_vars_set(name, nv); + tb_vars_set_ref(name, nv, ref); tb_value_free(&nv); self->dirty = false; } @@ -128,6 +138,7 @@ static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { if (!t || !tb_library_add(lib, &t->base)) return false; t = tb_type_block_create(rt, "Variables.Get", var_in, 1, any_out, 1, eval_var_get); if (!t || !tb_library_add(lib, &t->base)) return false; + tb_type_block_set_pure(t, TB_PURE_VAR, NULL, 1); /* executor pode compilar */ t = tb_type_block_create(rt, "Variables.DeclareLocal", var_set, 2, NULL, 0, eval_var_local); if (!t || !tb_library_add(lib, &t->base)) return false; t = tb_type_block_create(rt, "Variables.DeclareGlobal", var_set, 2, NULL, 0, eval_var_global); diff --git a/src/tb_vars.c b/src/tb_vars.c index 673cd80..af9eb97 100644 --- a/src/tb_vars.c +++ b/src/tb_vars.c @@ -4,14 +4,21 @@ */ #include #include +#include #include "tinyblocks/tb_vars.h" -typedef struct { char* name; TinyBlocks_Value val; } Var; +typedef struct { char* name; uint32_t hash; TinyBlocks_Value val; } Var; +/* Vetor na ordem de criacao (o painel de variaveis mostra nessa ordem) + + * indice hash (enderecamento aberto, guarda posicao+1; 0 = vazio). + * Ler uma variavel e o que a VM mais faz: sem o indice, cada leitura + * comparava o nome com todas as outras. */ typedef struct { Var* v; int n, cap; + int* idx; + int idx_cap; /* potencia de 2, >= 2 * cap */ } VarTable; struct TbVarScope { @@ -21,36 +28,72 @@ struct TbVarScope { }; static VarTable s_global; +static uint32_t s_gen = 1; /* muda quando uma variavel e criada/apagada ou um escopo morre (TbVarRef) */ static TbVarScope* s_cur = NULL; static TbVarScope* s_live = NULL; /* -- Tabela --- */ -static int table_find(const VarTable* t, const char* name) { - for (int i = 0; i < t->n; i++) if (!strcmp(t->v[i].name, name)) return i; +static uint32_t name_hash(const char* s) { + uint32_t h = 2166136261u; /* FNV-1a */ + for (; *s; s++) { h ^= (unsigned char)*s; h *= 16777619u; } + return h; +} + +static void index_rebuild(VarTable* t) { + if (!t->idx) return; + memset(t->idx, 0, (size_t)t->idx_cap * sizeof(int)); + uint32_t mask = (uint32_t)t->idx_cap - 1; + for (int i = 0; i < t->n; i++) { + uint32_t k = t->v[i].hash & mask; + while (t->idx[k]) k = (k + 1) & mask; + t->idx[k] = i + 1; + } +} + +static int table_find_h(const VarTable* t, const char* name, uint32_t h) { + if (!t->idx) return -1; + uint32_t mask = (uint32_t)t->idx_cap - 1; + for (uint32_t k = h & mask; t->idx[k]; k = (k + 1) & mask) { + const Var* x = &t->v[t->idx[k] - 1]; + if (x->hash == h && !strcmp(x->name, name)) return t->idx[k] - 1; + } return -1; } + static Var* table_put(VarTable* t, const char* name, TinyBlocks_Value v) { - int i = table_find(t, name); + uint32_t h = name_hash(name); + int i = table_find_h(t, name, h); if (i >= 0) { - tb_value_free(&t->v[i].val); - t->v[i].val = tb_value_clone(v); + TinyBlocks_Value old = t->v[i].val; + t->v[i].val = tb_value_clone(v); /* clona antes: v pode ser o proprio valor */ + tb_value_free(&old); return &t->v[i]; } if (t->n == t->cap) { int nc = t->cap ? t->cap * 2 : 16; Var* nv = realloc(t->v, (size_t)nc * sizeof(Var)); if (!nv) return NULL; + int* ni = calloc((size_t)nc * 2, sizeof(int)); + if (!ni) { t->v = nv; t->cap = nc; return NULL; } + free(t->idx); t->v = nv; t->cap = nc; + t->idx = ni; t->idx_cap = nc * 2; + index_rebuild(t); } size_t len = strlen(name); char* nm = malloc(len + 1); if (!nm) return NULL; memcpy(nm, name, len + 1); + s_gen++; Var* x = &t->v[t->n++]; x->name = nm; + x->hash = h; x->val = tb_value_clone(v); + uint32_t mask = (uint32_t)t->idx_cap - 1, k = h & mask; + while (t->idx[k]) k = (k + 1) & mask; + t->idx[k] = t->n; return x; } @@ -59,21 +102,28 @@ static void table_remove(VarTable* t, int i) { tb_value_free(&t->v[i].val); memmove(&t->v[i], &t->v[i + 1], (size_t)(t->n - i - 1) * sizeof(Var)); t->n--; + index_rebuild(t); /* posicoes mudaram (apagar e raro) */ + s_gen++; } static void table_clear(VarTable* t) { - while (t->n > 0) table_remove(t, t->n - 1); + s_gen++; + for (int i = 0; i < t->n; i++) { free(t->v[i].name); tb_value_free(&t->v[i].val); } + t->n = 0; free(t->v); + free(t->idx); t->v = NULL; t->cap = 0; + t->idx = NULL; t->idx_cap = 0; } /* Tabela onde `name` existe, do escopo atual para fora; NULL se nenhuma */ static VarTable* where(const char* name, int* idx) { + uint32_t h = name_hash(name); for (TbVarScope* s = s_cur; s; s = s->parent) { - int i = table_find(&s->t, name); + int i = table_find_h(&s->t, name, h); if (i >= 0) { *idx = i; return &s->t; } } - int i = table_find(&s_global, name); + int i = table_find_h(&s_global, name, h); if (i >= 0) { *idx = i; return &s_global; } return NULL; } @@ -96,6 +146,7 @@ void tb_vars_scope_free(TbVarScope* s) { for (TbVarScope* o = s_live; o; o = o->next_live) /* filhos perdem o pai */ if (o->parent == s) o->parent = NULL; if (s_cur == s) s_cur = NULL; + s_gen++; table_clear(&s->t); free(s); } @@ -112,6 +163,40 @@ const TinyBlocks_Value* tb_vars_get(const char* name) { return t ? &t->v[i].val : NULL; } +/* Cache valido: mesma geracao e o nome confere (o nome do bloco pode mudar) */ +static Var* ref_hit(const char* name, const TbVarRef* ref) { + if (!ref || ref->gen != s_gen || ref->scope != s_cur || !ref->table) return NULL; + Var* x = &((VarTable*)ref->table)->v[ref->idx]; + if (ref->fixed && ref->name == name) return x; /* nome fixo (codigo compilado) */ + return strcmp(x->name, name) == 0 ? x : NULL; +} + +const TinyBlocks_Value* tb_vars_get_ref(const char* name, TbVarRef* ref) { + if (!name || !name[0]) return NULL; + Var* x = ref_hit(name, ref); + if (x) return &x->val; + int i; + VarTable* t = where(name, &i); + if (!t) return NULL; + if (ref) { ref->gen = s_gen; ref->scope = s_cur; ref->table = t; ref->idx = i; ref->name = name; } + return &t->v[i].val; +} + +void tb_vars_set_ref(const char* name, TinyBlocks_Value v, TbVarRef* ref) { + if (!name || !name[0]) return; + Var* x = ref_hit(name, ref); + if (!x) { + tb_vars_set(name, v); + int i; + VarTable* t = where(name, &i); + if (t && ref) { ref->gen = s_gen; ref->scope = s_cur; ref->table = t; ref->idx = i; ref->name = name; } + return; + } + TinyBlocks_Value old = x->val; + x->val = tb_value_clone(v); + tb_value_free(&old); +} + bool tb_vars_exists(const char* name) { return tb_vars_get(name) != NULL; } void tb_vars_set(const char* name, TinyBlocks_Value v) {