From 339b8aef48c4ecb371f3f2f4abda41f6b9a3abd2 Mon Sep 17 00:00:00 2001 From: Gunnar Beutner Date: Sun, 29 Mar 2015 22:26:07 +0200 Subject: [PATCH] Avoid unnecessary allocations in ScriptFrame::SetCurrentFrame --- lib/base/scriptframe.cpp | 43 +++++++++++++++++++++++++++------------- lib/base/scriptframe.hpp | 7 ++++--- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/lib/base/scriptframe.cpp b/lib/base/scriptframe.cpp index 8e976c9b2..da03a99a0 100644 --- a/lib/base/scriptframe.cpp +++ b/lib/base/scriptframe.cpp @@ -22,39 +22,54 @@ using namespace icinga; -boost::thread_specific_ptr ScriptFrame::m_CurrentFrame; +boost::thread_specific_ptr > ScriptFrame::m_ScriptFrames; ScriptFrame::ScriptFrame(void) : Locals(new Dictionary()), Self(ScriptGlobal::GetGlobals()) { - NextFrame = GetCurrentFrame(); - SetCurrentFrame(this); + PushFrame(this); } ScriptFrame::ScriptFrame(const Value& self) : Locals(new Dictionary()), Self(self) { - NextFrame = GetCurrentFrame(); - SetCurrentFrame(this); + PushFrame(this); } ScriptFrame::~ScriptFrame(void) { - ASSERT(GetCurrentFrame() == this); - SetCurrentFrame(NextFrame); + ScriptFrame *frame = PopFrame(); + ASSERT(frame == this); } ScriptFrame *ScriptFrame::GetCurrentFrame(void) { - ScriptFrame **pframe = m_CurrentFrame.get(); + std::stack *frames = m_ScriptFrames.get(); - if (pframe) - return *pframe; - else - return NULL; + ASSERT(!frames->empty()); + return frames->top(); } -void ScriptFrame::SetCurrentFrame(ScriptFrame *frame) +ScriptFrame *ScriptFrame::PopFrame(void) { - m_CurrentFrame.reset(new ScriptFrame *(frame)); + std::stack *frames = m_ScriptFrames.get(); + + ASSERT(!frames->empty()); + + ScriptFrame *frame = frames->top(); + frames->pop(); + + return frame; +} + +void ScriptFrame::PushFrame(ScriptFrame *frame) +{ + std::stack *frames = m_ScriptFrames.get(); + + if (!frames) { + frames = new std::stack(); + m_ScriptFrames.reset(frames); + } + + frames->push(frame); } diff --git a/lib/base/scriptframe.hpp b/lib/base/scriptframe.hpp index 73a67d248..f4e47151a 100644 --- a/lib/base/scriptframe.hpp +++ b/lib/base/scriptframe.hpp @@ -23,6 +23,7 @@ #include "config/i2-config.hpp" #include "base/dictionary.hpp" #include +#include namespace icinga { @@ -31,7 +32,6 @@ struct I2_BASE_API ScriptFrame { Dictionary::Ptr Locals; Value Self; - ScriptFrame *NextFrame; ScriptFrame(void); ScriptFrame(const Value& self); @@ -40,9 +40,10 @@ struct I2_BASE_API ScriptFrame static ScriptFrame *GetCurrentFrame(void); private: - static boost::thread_specific_ptr m_CurrentFrame; + static boost::thread_specific_ptr > m_ScriptFrames; - static void SetCurrentFrame(ScriptFrame *frame); + inline static void PushFrame(ScriptFrame *frame); + inline static ScriptFrame *PopFrame(void); }; }