python: intern member-function names for PyCallClassMemberFunc

Per-frame UI callbacks (OnUpdate/OnRender/...) looked up methods with
PyObject_GetAttrString, building a new PyString each call. Names are
now interned once and cached; Py_AtExit drops the cache so a
Py_Finalize/Py_Initialize cycle never reuses stale objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-12 16:42:47 +09:00
co-authored by Claude Opus 5.5
parent 989f356c2e
commit 699ac058f5
+50 -1
View File
@@ -3,6 +3,8 @@
#include <Python.h>
#include "PortPythonPointer.h"
#include <string>
#include <string_view>
#include <unordered_map>
#include <cstdarg>
#include <cstdio>
@@ -216,6 +218,52 @@ inline bool PyTuple_GetBoolean(PyObject* poArgs, int pos, bool* ret)
return true;
}
// Interned method-name strings: UI windows call OnUpdate/OnRender/... every frame, and
// PyObject_GetAttrString would build a fresh PyString per call. The cache is dropped through
// Py_AtExit, so a Py_Finalize/Py_Initialize cycle never sees stale objects.
struct __PyNameHash
{
using is_transparent = void;
size_t operator()(std::string_view s) const noexcept { return std::hash<std::string_view>{}(s); }
};
inline std::unordered_map<std::string, PyObject*, __PyNameHash, std::equal_to<>>& __PyNameCache()
{
static std::unordered_map<std::string, PyObject*, __PyNameHash, std::equal_to<>> cache;
return cache;
}
inline bool& __PyNameCacheRegistered()
{
static bool registered = false;
return registered;
}
inline void __PyClearNameCache()
{
// Runs inside Py_Finalize after the interpreter released its objects; only forget the pointers.
__PyNameCache().clear();
__PyNameCacheRegistered() = false;
}
inline PyObject* __PyInternedName(const char* c_szName)
{
auto& cache = __PyNameCache();
auto it = cache.find(std::string_view(c_szName));
if (it != cache.end())
return it->second;
if (!__PyNameCacheRegistered())
{
if (Py_AtExit(__PyClearNameCache) != 0)
return nullptr;
__PyNameCacheRegistered() = true;
}
PyObject* poName = PyString_InternFromString(c_szName);
if (!poName)
{
PyErr_Clear();
return nullptr;
}
cache.emplace(c_szName, poName); // the cache owns this reference
return poName;
}
inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_szFunc, PyObject* poArgs, PyObject** ppoRet)
{
if (!poClass)
@@ -224,7 +272,8 @@ inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_s
return false;
}
PyObject * poFunc = PyObject_GetAttrString(poClass, (char *)c_szFunc);
PyObject * poName = __PyInternedName(c_szFunc);
PyObject * poFunc = poName ? PyObject_GetAttr(poClass, poName) : PyObject_GetAttrString(poClass, (char *)c_szFunc);
if (!poFunc)
{
PyErr_Clear();