Python字符串驻留的原理探究

367次阅读
没有评论

Python字符串驻留的原理探究

Python字符串驻留的原理说明

在CPython中,字符串引用由一个名为interned的Python字典存储、访问和管理。当第一次调用常驻字符串时,字典被延迟初始化,并保存对所有常驻字符串对象的引用。

Python字符串驻留的原理实例

负责常驻字符串的核心函数是PyUnicode_InternInPlace,它是在unicodeobject.c中定义的,调用时会创建一个interned的字典来容纳所有常驻字符串,然后在参数中注册对象,使它们的键和值使用相同的对象引用。

以下函数片段显示了 Python 实现字符串驻留的过程。

  void
  PyUnicode_InternInPlace(PyObject **p)
  {
      PyObject *s = *p;
  
      .........
  
      // Lazily build the dictionary to hold interned Strings
      if (interned == NULL) {
          interned = PyDict_New();
          if (interned == NULL) {
              PyErr_Clear();
              return;
          }
      }
  
      PyObject *t;
  
      // Make an entry to the interned dictionary for the
      // given object
      t = PyDict_SetDefault(interned, s, s);
  
      .........
 
      // The two references in interned dict (key and value) are
      // not counted by refcnt.
      // unicode_dealloc() and _PyUnicode_ClearInterned() take
      // care of this.
      Py_SET_REFCNT(s, Py_REFCNT(s) - 2);
  
      // Set the state of the string to be INTERNED
      _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
  }

以上就是Python字符串驻留的原理探究,希望能对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-04发表,共计1105字。
新手QQ群:570568346,欢迎进群讨论 Python51学习