Update int object to cache values between -1 and 255 by default.
This adds the `Int::new_obj_uncached()` function, which will create a new Int object without caching it. The `Int::new_obj()` will cache the value if it inclusively lies between -1 and 255. This is a minor optimization that should hopefully go a long way with speed and memory footprint. Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
@@ -4,11 +4,21 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use shredder::Scan;
|
use shredder::Scan;
|
||||||
use std::fmt::{self, Debug, Formatter};
|
use std::{collections::HashMap, fmt::{self, Debug, Formatter}, sync::Mutex};
|
||||||
|
|
||||||
|
/// Integer object ref type alias.
|
||||||
pub type IntRef = ObjRef<Int>;
|
pub type IntRef = ObjRef<Int>;
|
||||||
|
|
||||||
|
/// The native integer value type alias.
|
||||||
pub type IntValue = i128;
|
pub type IntValue = i128;
|
||||||
|
|
||||||
|
const INT_MIN_CACHE: IntValue = -1;
|
||||||
|
const INT_MAX_CACHE: IntValue = 255;
|
||||||
|
static INT_VALUE_CACHE: Lazy<Mutex<HashMap<IntValue, IntRef>>> = Lazy::new(||
|
||||||
|
Default::default()
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Integer object.
|
||||||
#[derive(Scan)]
|
#[derive(Scan)]
|
||||||
pub struct Int {
|
pub struct Int {
|
||||||
value: IntValue,
|
value: IntValue,
|
||||||
@@ -17,8 +27,25 @@ pub struct Int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Int {
|
impl Int {
|
||||||
pub fn new_obj(value: IntValue) -> ObjRef<Self> {
|
/// Create a newly allocated integer object on the heap.
|
||||||
// TODO(cache) : cache int values
|
///
|
||||||
|
/// This will look up the integer in the local cache of integers and return the cached value.
|
||||||
|
pub fn new_obj(value: IntValue) -> IntRef {
|
||||||
|
// before making the int value, check if it exists in the cache
|
||||||
|
if value >= INT_MIN_CACHE && value <= INT_MAX_CACHE {
|
||||||
|
let mut cache = INT_VALUE_CACHE.lock().unwrap();
|
||||||
|
cache.entry(value)
|
||||||
|
.or_insert_with(|| Int::new_obj_uncached(value))
|
||||||
|
.clone()
|
||||||
|
} else {
|
||||||
|
Int::new_obj_uncached(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a newly allocated integer object on the heap.
|
||||||
|
///
|
||||||
|
/// This will look up the integer in the local cache of integers.
|
||||||
|
pub fn new_obj_uncached(value: IntValue) -> IntRef {
|
||||||
self_referring_obj! {
|
self_referring_obj! {
|
||||||
Self {
|
Self {
|
||||||
value,
|
value,
|
||||||
|
|||||||
Reference in New Issue
Block a user