python / python/cpython

Adjust the value in objects' insertion order array to the index - position.

Open
#138,453 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

3.15 interpreter-core performance type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Currently, we store an array of bytes at the end of the inline value array of objects to record the insertion order.
This is expensive as we need to compute not only the value to insert, but where to insert it. Here's the code:

     PyDictValues *values = _PyObject_InlineValues(owner_o);
     Py_ssize_t index = value_ptr - values->values;
     _PyDictValues_AddToInsertionOrder(values, index);

_PyObject_InlineValues requires some lookup, as it depends on tp->basicsize

    return (PyDictValues *)((char *)obj + tp->tp_basicsize);

but it is _PyDictValues_AddToInsertionOrder that is the slowest:

    int size = values->size;
    uint8_t *array = (uint8_t *)&values->values[values->capacity];
    array[size] = (uint8_t)ix;
    values->size = size+1;

If instead of storing the delta of the index and position, instead of just the index, for the majority of objects the insert order array will go from { 0, 1, 2, 3, 4, ... } to { 0, 0, 0, 0, 0, ... }
And if the delta is zero, we don't need to store anything.

     PyDictValues *values = _PyObject_InlineValues(owner_o);
     Py_ssize_t index = value_ptr - values->values;
     Py_ssize_t delta = index - values->size;
     if (delta != 0) {
        /* This is the expensive part */
        _PyDictValues_AddToInsertionOrder(values, delta);
    }
    values->size++;

In the JIT we can track the size of the inline values, and know when delta will be zero. Reducing the above code to

    values->size = KNOWN_SIZE;

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing _PyObject_InlineValues and _PyDictValues_AddToInsertionOrder, then examine the JIT path described in the issue to understand how inline-value size is tracked. Done means insertion-order storage uses the proposed zero-delta behavior without changing object ordering, and the affected runtime behavior remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend, performance
Issue type
Refactor
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.