Skip to content

Commit 41a956a

Browse files
committed
fast-path hash() for exact PyStr
str.__hash__ can’t be overridden, so for exact PyStr instances we skip the attribute lookup and MRO walk and call the string hash directly. This reduces overhead on hot paths (e.g. dict/set key hashing) while keeping subclass semantics intact (downcast_ref_if_exact).
1 parent a9a9e3b commit 41a956a

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

vm/src/protocol/object.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,11 @@ impl PyObject {
642642
}
643643

644644
pub fn hash(&self, vm: &VirtualMachine) -> PyResult<PyHash> {
645+
// __hash__ function in str cannot be overwritten
646+
if let Some(pystr) = self.downcast_ref_if_exact::<PyStr>(vm) {
647+
return Ok(pystr.hash(vm));
648+
}
649+
645650
let hash = self.get_class_attr(identifier!(vm, __hash__)).unwrap();
646651
if vm.is_none(&hash) {
647652
return Err(vm.new_exception_msg(

0 commit comments

Comments
 (0)