• 技术文章 >Python技术 >Python基础教程

    Python如何清理驻留的字符串

    小妮浅浅小妮浅浅2021-02-26 16:16:28原创2960

    1、说明

    清除函数从interneddictionary遍历所有字符串,调整这些对象的引用计数,并将它们标记为NOT_INTERNED,这样垃圾回收就可以了。当所有的字符串都被标记为NOT_INTERNED时,将清空并删除interned字典。

    2、清理实例

    这个清理函数就是_PyUnicode_ClearInterned,在 unicodeobject.c 中定义。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    void

     _PyUnicode_ClearInterned(PyThreadState *tstate)

     {

         .........

      

         // Get all the keys to the interned dictionary

         PyObject *keys = PyDict_Keys(interned);

      

         .........

      

         // Interned Unicode strings are not forcibly deallocated;

         // rather, we give them their stolen references back

         // and then clear and DECREF the interned dict.

      

         for (Py_ssize_t i = 0; i < n; i++) {

             PyObject *s = PyList_GET_ITEM(keys, i);

      

             .........

      

             switch (PyUnicode_CHECK_INTERNED(s)) {

             case SSTATE_INTERNED_IMMORTAL:

                 Py_SET_REFCNT(s, Py_REFCNT(s) + 1);

                 break;

             case SSTATE_INTERNED_MORTAL:

                 // Restore the two references (key and value) ignored

                 // by PyUnicode_InternInPlace().

                 Py_SET_REFCNT(s, Py_REFCNT(s) + 2);

                 break;

             case SSTATE_NOT_INTERNED:

                 /* fall through */

             default:

                 Py_UNREACHABLE();

             }

      

             // marking the string to be NOT_INTERNED

             _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;

         }

      

         // decreasing the reference to the initialized and

         // access keys object.

         Py_DECREF(keys);

      

         // clearing the dictionary

         PyDict_Clear(interned);

      

         // clearing the object interned

         Py_CLEAR(interned);

     }

    以上就是Python清理驻留字符串的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python字符串驻留
    上一篇:Python如何判定字符串被驻留 下一篇:Python selenium的详细安装整理

    相关文章推荐

    • Python列表常见操作总结• Python列表两种排序类型的实现• Python字符串有哪几种表示形式• Python如何判定字符串被驻留

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网