mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
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
This commit is contained in:
1 parent
9cdc869521
commit
35a10ada02
2 files changed
+17
-1
No files matched your search
@@ -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<Self>, _vm: &VirtualMachine) -> PyResult<String> {
|
||||
Ok(zelf.value.to_string())
|
||||
Ok(zelf.to_str_radix_10())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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::<PyInt>(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,
|
||||
|
||||
Reference in new issue
Block a user