Skip to main content

layout_flex_chain_bench/
layout_flex_chain_bench.rs

1use std::time::Instant;
2use ui_layout::*;
3
4/// display だけ指定したノードを作る
5fn node(display: Display) -> LayoutNode {
6    LayoutNode::new(Style {
7        display,
8        spacing: Spacing {
9            margin_left: Length::Px(2.0),
10            margin_right: Length::Px(2.0),
11            padding_left: Length::Px(1.0),
12            padding_right: Length::Px(1.0),
13            border_left: Length::Px(1.0),
14            border_right: Length::Px(1.0),
15            ..Default::default()
16        },
17        size: SizeStyle {
18            min_width: Length::Px(0.0),
19            max_width: Length::Px(10_000.0),
20            ..Default::default()
21        },
22        ..Default::default()
23    })
24}
25
26/// Flex の深い連鎖を作る
27fn make_flex_chain(depth: usize, max_depth: usize) -> LayoutNode {
28    let mut root = node(Display::Flex {
29        flex_direction: FlexDirection::Row,
30    });
31
32    if depth >= max_depth {
33        root.children.push(node(Display::Block));
34        return root;
35    }
36
37    // 子1: Block(文脈は切れない)
38    let mut block = node(Display::Block);
39
40    // Block の中にさらに Flex
41    block.children.push(make_flex_chain(depth + 1, max_depth));
42
43    root.children.push(block);
44    root
45}
46
47/// 実サイトっぽい「枝」を追加
48fn make_branch(depth: usize, max_depth: usize) -> LayoutNode {
49    let mut flex = node(Display::Flex {
50        flex_direction: FlexDirection::Column,
51    });
52
53    // 子は少ない(1〜2)
54    flex.children.push(make_flex_chain(depth, max_depth));
55
56    if depth % 3 == 0 {
57        let mut side = node(Display::Block);
58        side.children.push(node(Display::Block));
59        flex.children.push(side);
60    }
61
62    flex
63}
64
65fn make_tree() -> LayoutNode {
66    let mut root = node(Display::Block);
67
68    // 上位は Block
69    root.children.push(node(Display::Block));
70
71    // 問題の塊
72    root.children.push(make_branch(0, 20));
73
74    root
75}
76
77fn main() {
78    println!("flex-chain layout benchmark");
79    println!("----------------------------");
80
81    let mut root = make_tree();
82
83    let t1 = {
84        let start = Instant::now();
85        LayoutEngine::layout(&mut root, 800.0, 600.0);
86        start.elapsed()
87    };
88
89    println!("1st layout: {:?}", t1);
90
91    let t2 = {
92        let start = Instant::now();
93        LayoutEngine::layout(&mut root, 800.0, 600.0);
94        start.elapsed()
95    };
96
97    println!("2nd layout: {:?}", t2);
98}