summaryrefslogtreecommitdiff
path: root/preact/demo/profiler.js
blob: bb4426904704d3b5d3d78948e95fc087d5dbf6ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { createElement, Component, options } from 'preact';

function getPrimes(max) {
	let sieve = [],
		i,
		j,
		primes = [];
	for (i = 2; i <= max; ++i) {
		if (!sieve[i]) {
			// i has not been marked -- it is prime
			primes.push(i);
			for (j = i << 1; j <= max; j += i) {
				sieve[j] = true;
			}
		}
	}
	return primes.join('');
}

function Foo(props) {
	return <div>{props.children}</div>;
}

function Bar() {
	getPrimes(10000);
	return (
		<div>
			<span>...yet another component</span>
		</div>
	);
}

function PrimeNumber(props) {
	// Slow down rendering of this component
	getPrimes(10);

	return (
		<div>
			<span>I'm a slow component</span>
			<br />
			{props.children}
		</div>
	);
}

export default class ProfilerDemo extends Component {
	constructor() {
		super();
		this.onClick = this.onClick.bind(this);
		this.state = { counter: 0 };
	}

	componentDidMount() {
		options._diff = vnode => (vnode.startTime = performance.now());
		options.diffed = vnode => (vnode.endTime = performance.now());
	}

	componentWillUnmount() {
		delete options._diff;
		delete options.diffed;
	}

	onClick() {
		this.setState(prev => ({ counter: ++prev.counter }));
	}

	render() {
		return (
			<div class="foo">
				<h1>⚛ Preact</h1>
				<p>
					<b>Devtools Profiler integration 🕒</b>
				</p>
				<Foo>
					<PrimeNumber>
						<Foo>I'm a fast component</Foo>
						<Bar />
					</PrimeNumber>
				</Foo>
				<Foo>I'm the fastest component 🎉</Foo>
				<span>Counter: {this.state.counter}</span>
				<br />
				<br />
				<button onClick={this.onClick}>Force re-render</button>
			</div>
		);
	}
}