Skip to content

Commit 3e6f18c

Browse files
authored
Merge pull request RustPython#1898 from youknowone/cache-str-len
Cache str.len()
2 parents 3937e84 + 5396053 commit 3e6f18c

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

vm/src/obj/objstr.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ use crate::vm::VirtualMachine;
5050
pub struct PyString {
5151
value: String,
5252
hash: AtomicCell<Option<pyhash::PyHash>>,
53+
len: AtomicCell<Option<usize>>,
5354
}
5455
impl ThreadSafe for PyString {}
5556

@@ -71,6 +72,7 @@ impl From<String> for PyString {
7172
PyString {
7273
value: s,
7374
hash: AtomicCell::default(),
75+
len: AtomicCell::default(),
7476
}
7577
}
7678
}
@@ -294,20 +296,21 @@ impl PyString {
294296

295297
#[pymethod(name = "__hash__")]
296298
fn hash(&self) -> pyhash::PyHash {
297-
match self.hash.load() {
298-
Some(hash) => hash,
299-
None => {
300-
let hash = pyhash::hash_value(&self.value);
301-
self.hash.store(Some(hash));
302-
hash
303-
}
304-
}
299+
self.hash.load().unwrap_or_else(|| {
300+
let hash = pyhash::hash_value(&self.value);
301+
self.hash.store(Some(hash));
302+
hash
303+
})
305304
}
306305

307306
#[pymethod(name = "__len__")]
308307
#[inline]
309308
fn len(&self) -> usize {
310-
self.value.chars().count()
309+
self.len.load().unwrap_or_else(|| {
310+
let len = self.value.chars().count();
311+
self.len.store(Some(len));
312+
len
313+
})
311314
}
312315

313316
#[pymethod(name = "__sizeof__")]

0 commit comments

Comments
 (0)