1 | <?php |
---|
2 | |
---|
3 | class FakePost { |
---|
4 | public function __construct($ID, $post_parent) { |
---|
5 | $this->ID = $ID; |
---|
6 | $this->post_parent = $post_parent; |
---|
7 | } |
---|
8 | } |
---|
9 | |
---|
10 | |
---|
11 | function get_page_children( $page_id, $pages ) { |
---|
12 | // build a hash of ID -> children |
---|
13 | $children = array(); |
---|
14 | foreach ( (array) $pages as $p ) { |
---|
15 | $children[ intval( $p->post_parent ) ][] = $p; |
---|
16 | } |
---|
17 | |
---|
18 | $post_list = array(); |
---|
19 | if( array_key_exists( $page_id, $children ) ) { |
---|
20 | $to_look = array_reverse( $children[ $page_id ] ); |
---|
21 | // while we still have posts to_look add them to the list |
---|
22 | while ( $to_look ) { |
---|
23 | $p = array_pop( $to_look ); |
---|
24 | $post_list[] = $p; |
---|
25 | if ( array_key_exists( $p->ID, $children ) ) { |
---|
26 | foreach ( array_reverse( $children[ $p->ID ] ) as $child ) { |
---|
27 | $to_look[] = $child; |
---|
28 | } |
---|
29 | } |
---|
30 | } |
---|
31 | } |
---|
32 | |
---|
33 | return $post_list; |
---|
34 | } |
---|
35 | |
---|
36 | function old_get_page_children($page_id, $pages) { |
---|
37 | $page_list = array(); |
---|
38 | foreach ( (array) $pages as $page ) { |
---|
39 | if ( $page->post_parent == $page_id ) { |
---|
40 | $page_list[] = $page; |
---|
41 | if ( $children = old_get_page_children($page->ID, $pages) ) { |
---|
42 | $page_list = array_merge($page_list, $children); |
---|
43 | } |
---|
44 | } |
---|
45 | } |
---|
46 | return $page_list; |
---|
47 | } |
---|
48 | |
---|
49 | function tests() { |
---|
50 | $pages = []; |
---|
51 | $pages[] = new FakePost(1, 0); |
---|
52 | $pages[] = new FakePost(2, 0); |
---|
53 | $pages[] = new FakePost(3, 2); |
---|
54 | $pages[] = new FakePost(4, 2); |
---|
55 | $pages[] = new FakePost(5, 0); |
---|
56 | for ($i=6; $i < 1000; $i++) { |
---|
57 | $pages[] = new FakePost($i, rand(0, $i-1)); |
---|
58 | } |
---|
59 | $max_depth = 50; |
---|
60 | for ($i=1000; $i < (1000 + $max_depth); $i++) { |
---|
61 | $pages[] = new FakePost($i, $i-1); |
---|
62 | } |
---|
63 | for ($i=(1000 + $max_depth); $i < 2000; $i++) { |
---|
64 | $pages[] = new FakePost($i, 5); |
---|
65 | } |
---|
66 | for ($i=2000; $i < 4000; $i++) { |
---|
67 | $pages[] = new FakePost($i, 1); |
---|
68 | } |
---|
69 | |
---|
70 | for ($i=0; $i < 8; $i++) { |
---|
71 | $time = []; |
---|
72 | $r = []; |
---|
73 | |
---|
74 | $time_start = microtime(true); |
---|
75 | $r[] = get_page_children($i, $pages); |
---|
76 | $time[] = (int) ((microtime(true) - $time_start) * 1000); |
---|
77 | |
---|
78 | $time_start = microtime(true); |
---|
79 | $r[] = old_get_page_children($i, $pages); |
---|
80 | $time[] = (int) ((microtime(true) - $time_start) * 1000); |
---|
81 | |
---|
82 | echo ($r[0] == $r[1])?'Equal':'Different'; |
---|
83 | echo " $time[0] ms (new), $time[1] ms (old)\n"; |
---|
84 | } |
---|
85 | } |
---|
86 | |
---|
87 | tests(); |
---|