1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //! A performance testing suite for ylong_json.
15 //!
16 //! This performance testing suite compares the speed of the `ylong_json` crate
17 //! with `serde_json` for parsing JSON text and converting JSON objects into
18 //! strings. The test is run multiple times as defined by `LOOPS_NUM`.
19 //!
20 //! Example JSON used in this test represents an image object with various properties.
21 
22 use serde_json::Value;
23 use std::str::FromStr;
24 use std::time::Instant;
25 use ylong_json::JsonValue;
26 
27 const LOOPS_NUM: usize = 10000;
28 const JSON_TEXT: &str = r#"
29 {
30     "Image": {
31         "Width":  800,
32         "Height": 600,
33         "Title":  "View from 15th Floor",
34         "Thumbnail": {
35             "Url":    "http://www.example.com/image/481989943",
36             "Height": 125,
37             "Width":  100
38         },
39         "Animated" : false,
40         "IDs": [116, 943, 234, 38793]
41     }
42 }
43 "#;
44 
main()45 fn main() {
46     let value = JsonValue::from_str(JSON_TEXT).unwrap();
47     println!("{}", value.to_compact_string().unwrap());
48 
49     let st = Instant::now();
50     for _ in 0..LOOPS_NUM {
51         let value = JsonValue::from_str(JSON_TEXT).unwrap();
52         let _ = value.to_compact_string();
53     }
54     let ed = Instant::now();
55     println!(
56         "ylong_json: {}ms",
57         ed.duration_since(st).as_secs_f64() * 1000f64
58     );
59 
60     let value: Value = serde_json::from_str(JSON_TEXT).unwrap();
61     println!("{value}");
62 
63     let st = Instant::now();
64     for _ in 0..LOOPS_NUM {
65         let value: Value = serde_json::from_str(JSON_TEXT).unwrap();
66         format!("{value}");
67     }
68     let ed = Instant::now();
69     println!(
70         "serde_json: {}ms",
71         ed.duration_since(st).as_secs_f64() * 1000f64
72     );
73 }
74