-
Bug DescriptionIt is slower than pure python. Steps to Reproduce
Backtraceno Your operating system and versionDebian testing Your Python version (
|
Beta Was this translation helpful? Give feedback.
Answered by
mejrs
Apr 2, 2022
Replies: 1 comment 6 replies
-
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, "there"), intern!(py, "hello"))?;
Ok(())
} beats the Python function in my benchmark. |
Beta Was this translation helpful? Give feedback.
6 replies
Answer selected by
davidhewitt
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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