From 35a10ada021b87638a3d091982b08e40b11e62ea Mon Sep 17 00:00:00 2001 From: "Jeong, YunWon" <69878+youknowone@users.noreply.github.com> Date: Mon, 2 Mar 2026 11:02:49 +0900 Subject: [PATCH] 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 --- crates/vm/src/builtins/int.rs | 11 ++++++++++- crates/vm/src/protocol/object.rs | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index 0bf7372bb..788f450df 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -267,6 +267,15 @@ impl PyInt { &self.value } + /// Fast decimal string conversion, using i64 path when possible. + #[inline] + pub fn to_str_radix_10(&self) -> String { + match self.value.to_i64() { + Some(i) => i.to_string(), + None => self.value.to_string(), + } + } + // _PyLong_AsUnsignedLongMask pub fn as_u32_mask(&self) -> u32 { let v = self.as_bigint(); @@ -603,7 +612,7 @@ impl Comparable for PyInt { impl Representable for PyInt { #[inline] fn repr_str(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - Ok(zelf.value.to_string()) + Ok(zelf.to_str_radix_10()) } } diff --git a/crates/vm/src/protocol/object.rs b/crates/vm/src/protocol/object.rs index 75b34c29c..ad33d9a26 100644 --- a/crates/vm/src/protocol/object.rs +++ b/crates/vm/src/protocol/object.rs @@ -375,6 +375,13 @@ impl PyObject { Ok(s) => return Ok(s.into_pyref()), Err(obj) => obj, }; + // Fast path for exact int: skip __str__ method resolution + let obj = match obj.downcast_exact::(vm) { + Ok(int) => { + return Ok(vm.ctx.new_str(int.to_str_radix_10())); + } + Err(obj) => obj, + }; // TODO: replace to obj.class().slots.str let str_method = match vm.get_special_method(&obj, identifier!(vm, __str__))? { Some(str_method) => str_method,