|
7 | 7 | <body> |
8 | 8 | <script> |
9 | 9 | /* Title: Conditionals |
10 | | - Description: pattern and antipattern of using if else |
11 | | -*/ |
| 10 | + * Description: pattern and antipattern of using if else |
| 11 | + */ |
12 | 12 |
|
13 | | -// NOTE: Paul Irish states that the first statement is only an antipattern when optimizing for |
14 | | -// low-bandwidth source (such as for a bookmarklet). |
15 | | -// Using the first statement will generally outperform the regex in a loop, and is faster than the |
16 | | -// object literal for lower numbers of conditions (they generally even out around 10 conditions). |
17 | | -// See http://jsperf.com/if-this-or-that |
| 13 | +/* NOTE: Paul Irish states that the first statement (normal pattern) is only an antipattern when optimizing for |
| 14 | + * low-bandwidth source (such as for a bookmarklet). |
| 15 | + * Using the normal pattern will generally outperform the regex (alternative method 1) in a loop, |
| 16 | + * and is faster than the object literal (alternative method 2) for lower numbers of conditions, |
| 17 | + * they generally even out around 10 conditions. |
| 18 | + * See http://jsperf.com/if-this-or-that |
| 19 | + */ |
18 | 20 |
|
19 | | -// Normal Pattern |
| 21 | +// normal pattern |
20 | 22 | if (type === 'foo' || type === 'bar' ) {} |
21 | 23 |
|
22 | 24 |
|
23 | | -/* alternative method 1 - regex test */ |
| 25 | +// alternative method 1 - regex test |
24 | 26 | if ( /^(foo|bar)$/.test(type) ) {} |
25 | 27 |
|
26 | 28 |
|
27 | | -/* alternative method 2 - object literal lookup (smaller if < 5 items) */ |
| 29 | +// alternative method 2 - object literal lookup (smaller if < 5 items) |
28 | 30 | if ( ({foo:1,bar:1})[type] ) {} |
29 | 31 |
|
30 | 32 |
|
31 | 33 | /* alternative method 3 - binary-search-like approach |
32 | | - This approach is best when there are ranges of values for which to test |
33 | | -*/ |
34 | | - |
| 34 | + * This approach is best when there are ranges of values for which to test |
| 35 | + */ |
35 | 36 | if (value == 0){ |
36 | 37 | return result0; |
37 | 38 | } else if (value == 1){ |
|
94 | 95 |
|
95 | 96 |
|
96 | 97 | /* alternative method 4 - object/array lookup tables |
97 | | - Most useful when there is logical mapping between a single key and a single value |
98 | | -*/ |
99 | | - |
| 98 | + * Most useful when there is logical mapping between a single key and a single value |
| 99 | + */ |
100 | 100 | if (value == 0) { |
101 | 101 | return result0; |
102 | 102 | } else if (value == 1) { |
|
111 | 111 | return results[value]; |
112 | 112 |
|
113 | 113 |
|
114 | | -// reference |
| 114 | +// References |
115 | 115 | // http://paulirish.com/2009/perf/ |
116 | 116 | </script> |
117 | 117 | </body> |
|
0 commit comments