Skip to content

object! performance could be improved #159

@pmnoxx

Description

@pmnoxx

I started using object! macro, but I noticed that it's performing poorly, due to unnecessary memory allocations. We can optimize the code, because we know the number of arguments we are going to put into the array.
Here are the results:

test object ... bench: 52,500,999 ns/iter (+/- 1,924,204)
test object_new ... bench: 33,950,158 ns/iter (+/- 685,775)

`
#![feature(test)]

extern crate test;
#[macro_use]
extern crate json;

use json::JsonValue;
use test::Bencher;


macro_rules! count {
() => (0usize);
( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
}

macro_rules! obj {
{} => ($crate::JsonValue::new_object());

{ $( $key:expr => $value:expr ),* } => {
    obj!( $(
        $key => $value,
    )* )
};

{ $( $key:expr => $value:expr, )* } => ({
    use json::object::Object;

    let cnt = count!( $( $key )* );
    let mut object = Object::with_capacity(cnt);
    $(
        object.insert($key, $value.into());
    )*

    JsonValue::Object(object)
})

}

#[bench]
fn object_new(b: &mut Bencher) {
b.iter(|| {
for it in 0..100_000 {
let mut val: JsonValue = obj! {
"data"=> obj!{
"arg1" => 23,
"arg2" => 44,
},
"test"=> 880032432,
"anki"=> JsonValue::Null,
};
}
});
}

#[bench]
fn object(b: &mut Bencher) {
b.iter(|| {
for it in 0..100_000 {
let mut val: JsonValue = object! {
"data"=> obj!{
"arg1" => 23,
"arg2" => 44,
},
"test"=> 880032432,
"anki"=> JsonValue::Null,
};
}
});
}

`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions