Skip to content

Commit 888e0ee

Browse files
authored
Add str(int) and repr(int) fast path using i64 conversion (#7302)
* Add str(int) and repr(int) fast path using i64 conversion - Skip __str__ method resolution for exact PyInt in PyObject::str() - Use i64::to_string() for small integers, BigInt::to_string() for large ones - ~36% improvement in str(int) benchmarks * Extract PyInt::to_str_radix_10() to deduplicate i64 fast path logic
1 parent 69fc75b commit 888e0ee

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

crates/vm/src/builtins/int.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,15 @@ impl PyInt {
267267
&self.value
268268
}
269269

270+
/// Fast decimal string conversion, using i64 path when possible.
271+
#[inline]
272+
pub fn to_str_radix_10(&self) -> String {
273+
match self.value.to_i64() {
274+
Some(i) => i.to_string(),
275+
None => self.value.to_string(),
276+
}
277+
}
278+
270279
// _PyLong_AsUnsignedLongMask
271280
pub fn as_u32_mask(&self) -> u32 {
272281
let v = self.as_bigint();
@@ -603,7 +612,7 @@ impl Comparable for PyInt {
603612
impl Representable for PyInt {
604613
#[inline]
605614
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
606-
Ok(zelf.value.to_string())
615+
Ok(zelf.to_str_radix_10())
607616
}
608617
}
609618

crates/vm/src/protocol/object.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,13 @@ impl PyObject {
375375
Ok(s) => return Ok(s.into_pyref()),
376376
Err(obj) => obj,
377377
};
378+
// Fast path for exact int: skip __str__ method resolution
379+
let obj = match obj.downcast_exact::<PyInt>(vm) {
380+
Ok(int) => {
381+
return Ok(vm.ctx.new_str(int.to_str_radix_10()));
382+
}
383+
Err(obj) => obj,
384+
};
378385
// TODO: replace to obj.class().slots.str
379386
let str_method = match vm.get_special_method(&obj, identifier!(vm, __str__))? {
380387
Some(str_method) => str_method,

0 commit comments

Comments
 (0)