Skip to content

PyDict.set_item is very slow. #2266

Answered by mejrs
songww asked this question in Questions
Apr 2, 2022 · 1 comments · 6 replies
Discussion options

You must be logged in to vote

This discrepancy is because I think your Python function reuses the strings, while the pyo3 function creates new strings for every call.

In fact, if you store the strings in a static, you can avoid that. Something like

macro_rules! intern {
    ($py: expr, $text: literal) => {{
        static INTERNED: GILOnceCell<Py<PyString>> = GILOnceCell::new();

        INTERNED.get_or_init($py, || {            
                PyString::new($py, $text).into()         
            }).as_ref($py)
    }}
}

#[pyfunction]
fn setitems_cached(py: Python<'_>) -> PyResult<()> {
    let d = pyo3::types::PyDict::new(py);
    d.set_item(intern!(py, "hello"), intern!(py, "there"))?;
    d.set_item(intern!(py, "…

Replies: 1 comment 6 replies

Comment options

You must be logged in to vote
6 replies
@adamreichold
Comment options

@adamreichold
Comment options

@adamreichold
Comment options

@adamreichold
Comment options

@songww
Comment options

Answer selected by davidhewitt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
4 participants
Converted from issue

This discussion was converted from issue #2264 on April 02, 2022 15:54.