@@ -8,7 +8,7 @@ use std::rc::Rc;
8
8
9
9
use num_bigint:: BigInt ;
10
10
use num_complex:: Complex64 ;
11
- use num_traits:: { One , Zero } ;
11
+ use num_traits:: { One , ToPrimitive , Zero } ;
12
12
13
13
use crate :: bytecode;
14
14
use crate :: dictdatatype:: DictKey ;
@@ -92,6 +92,9 @@ impl fmt::Display for PyObject<dyn PyObjectPayload> {
92
92
}
93
93
}
94
94
95
+ const INT_CACHE_POOL_MIN : i32 = -5 ;
96
+ const INT_CACHE_POOL_MAX : i32 = 256 ;
97
+
95
98
#[ derive( Debug ) ]
96
99
pub struct PyContext {
97
100
pub true_value : PyIntRef ,
@@ -104,6 +107,7 @@ pub struct PyContext {
104
107
105
108
pub types : TypeZoo ,
106
109
pub exceptions : exceptions:: ExceptionZoo ,
110
+ pub int_cache_pool : Vec < PyObjectRef > ,
107
111
}
108
112
109
113
pub type PyNotImplementedRef = PyRef < PyNotImplemented > ;
@@ -149,6 +153,10 @@ impl PyContext {
149
153
create_type ( "NotImplementedType" , & types. type_type , & types. object_type ) ;
150
154
let not_implemented = create_object ( PyNotImplemented , & not_implemented_type) ;
151
155
156
+ let int_cache_pool = ( INT_CACHE_POOL_MIN ..=INT_CACHE_POOL_MAX )
157
+ . map ( |v| create_object ( PyInt :: new ( BigInt :: from ( v) ) , & types. int_type ) . into_object ( ) )
158
+ . collect ( ) ;
159
+
152
160
let true_value = create_object ( PyInt :: new ( BigInt :: one ( ) ) , & types. bool_type ) ;
153
161
let false_value = create_object ( PyInt :: new ( BigInt :: zero ( ) ) , & types. bool_type ) ;
154
162
@@ -159,12 +167,13 @@ impl PyContext {
159
167
false_value,
160
168
not_implemented,
161
169
none,
170
+ empty_tuple,
162
171
ellipsis,
163
172
ellipsis_type,
164
173
165
174
types,
166
175
exceptions,
167
- empty_tuple ,
176
+ int_cache_pool ,
168
177
} ;
169
178
initialize_types ( & context) ;
170
179
@@ -364,7 +373,15 @@ impl PyContext {
364
373
self . types . object_type . clone ( )
365
374
}
366
375
376
+ #[ inline]
367
377
pub fn new_int < T : Into < BigInt > > ( & self , i : T ) -> PyObjectRef {
378
+ let i = i. into ( ) ;
379
+ if let Some ( i) = i. to_i32 ( ) {
380
+ if i >= INT_CACHE_POOL_MIN && i <= INT_CACHE_POOL_MAX {
381
+ let inner_idx = ( i - INT_CACHE_POOL_MIN ) as usize ;
382
+ return self . int_cache_pool [ inner_idx] . clone ( ) ;
383
+ }
384
+ }
368
385
PyObject :: new ( PyInt :: new ( i) , self . int_type ( ) , None )
369
386
}
370
387
0 commit comments