From ef3ee55d4216137ae87da314343e0e5e22d90b96 Mon Sep 17 00:00:00 2001 From: EvilSpirit Date: Wed, 14 Oct 2015 22:26:19 +0600 Subject: [PATCH] Optimize Expr::From(double) by statically allocating common constants. --- src/expr.cpp | 29 +++++++++++++++++++++++++++++ src/expr.h | 3 +++ 2 files changed, 32 insertions(+) diff --git a/src/expr.cpp b/src/expr.cpp index 8d6600d5..add6c8b4 100644 --- a/src/expr.cpp +++ b/src/expr.cpp @@ -219,6 +219,35 @@ Expr *Expr::From(hParam p) { } Expr *Expr::From(double v) { + // Statically allocate common constants. + // Note: this is only valid because AllocExpr() uses AllocTemporary(), + // and Expr* is never explicitly freed. + + if(v == 0.0) { + static Expr zero(0.0); + return &zero; + } + + if(v == 1.0) { + static Expr one(1.0); + return &one; + } + + if(v == -1.0) { + static Expr mone(-1.0); + return &mone; + } + + if(v == 0.5) { + static Expr half(0.5); + return ½ + } + + if(v == -0.5) { + static Expr mhalf(-0.5); + return &mhalf; + } + Expr *r = AllocExpr(); r->op = CONSTANT; r->x.v = v; diff --git a/src/expr.h b/src/expr.h index 30f7b266..d53b0b28 100644 --- a/src/expr.h +++ b/src/expr.h @@ -63,6 +63,9 @@ public: char c; } x; + Expr() { } + Expr(double v) : op(CONSTANT) { x.v = v; } + static inline Expr *AllocExpr(void) { return (Expr *)AllocTemporary(sizeof(Expr)); }