From 08eceb738236206639a7cb66e4e6406cce00a10a Mon Sep 17 00:00:00 2001 From: Bob Nystrom Date: Tue, 16 Aug 2016 07:24:04 -0700 Subject: [PATCH] Check for duplicates when adding constants. This saves a little memory, but, more importantly, allows us to support functions with large numbers of repeated constants. --- src/vm/wren_compiler.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/vm/wren_compiler.c b/src/vm/wren_compiler.c index a0d1cd30..1d4351a8 100644 --- a/src/vm/wren_compiler.c +++ b/src/vm/wren_compiler.c @@ -465,6 +465,17 @@ static int addConstant(Compiler* compiler, Value constant) { if (compiler->parser->hasError) return -1; + // See if we already have a constant for the value. If so, reuse it. + // TODO: This is O(n). Do something better? + for (int i = 0; i < compiler->fn->constants.count; i++) + { + if (wrenValuesEqual(constant, compiler->fn->constants.data[i])) + { + return i; + } + } + + // It's a new constant. if (compiler->fn->constants.count < MAX_CONSTANTS) { if (IS_OBJ(constant)) wrenPushRoot(compiler->parser->vm, AS_OBJ(constant));