{"openapi":"3.1.0","info":{"title":"Stack Exchange API","version":"1.0.0","description":"Search Stack Overflow and the Stack Exchange network — questions by relevance with scores, answer counts and tags, full question details, and user profiles with reputation, badges and location. Ideal for developer tools, tech-trend monitoring, Q&A aggregation and reputation lookups.","contact":{"name":"PremiumApi","url":"https://www.oanor.com/by/premiumapi"}},"servers":[{"url":"https://api.oanor.com/stackexchange-api","description":"oanor gateway"}],"tags":[{"name":"Stack Exchange"},{"name":"Questions"},{"name":"Users"},{"name":"Tags"},{"name":"Meta"}],"components":{"securitySchemes":{"oanorKey":{"type":"apiKey","in":"header","name":"x-oanor-key","description":"Get your key at https://www.oanor.com/developer/keys"}}},"security":[{"oanorKey":[]}],"paths":{"/v1/question":{"get":{"operationId":"get_v1_question","tags":["Stack Exchange"],"summary":"A question by id","description":"","parameters":[{"name":"id","in":"query","required":true,"description":"Numeric question id","schema":{"type":"string"},"example":"11227809"},{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"id":11227809,"link":"https://stackoverflow.com/questions/11227809/why-is-conditional-processing-of-a-sorted-array-faster-than-of-an-unsorted-array","tags":["java","c++","performance","cpu-architecture","branch-prediction"],"owner":"GManNickG","score":27530,"title":"Why is conditional processing of a sorted array faster than of an unsorted array?","created_at":"2012-06-27T13:51:36.000Z","view_count":1985304,"is_answered":true,"answer_count":26,"last_activity_at":"2026-04-08T05:35:32.000Z","accepted_answer_id":11227902},"meta":{"timestamp":"2026-05-30T06:33:29.921Z","request_id":"17f03b07-c69f-4aed-8065-159a7ff98e4d"},"status":"ok","message":"Question retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/search":{"get":{"operationId":"get_v1_search","tags":["Stack Exchange"],"summary":"Search questions by relevance","description":"","parameters":[{"name":"q","in":"query","required":true,"description":"Search text","schema":{"type":"string"},"example":"how to reverse a list"},{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"},{"name":"limit","in":"query","required":false,"description":"Max results (1-30)","schema":{"type":"string"},"example":"15"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"site":"stackoverflow","count":15,"query":"async await","results":[{"id":37576685,"link":"https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop","tags":["javascript","node.js","promise","async-await","ecmascript-2017"],"owner":"Saad","score":3351,"title":"Using async/await with a forEach loop","created_at":"2016-06-01T18:55:58.000Z","view_count":2476066,"is_answered":true,"answer_count":35,"last_activity_at":"2025-01-28T01:27:13.000Z","accepted_answer_id":37576787},{"id":14455293,"link":"https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await","tags":["c#",".net","asynchronous","async-await"],"owner":"Dan Dinu","score":1429,"title":"How and when to use ‘async’ and ‘await’","created_at":"2013-01-22T09:29:58.000Z","view_count":1314415,"is_answered":true,"answer_count":26,"last_activity_at":"2025-12-18T14:16:06.000Z","accepted_answer_id":19985988},{"id":35612428,"link":"https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel","tags":["javascript","node.js","asynchronous","ecmascript-6","babeljs"],"owner":"Victor Marchuk","score":923,"title":"Call async/await functions in parallel","created_at":"2016-02-24T20:28:46.000Z","view_count":602369,"is_answered":true,"answer_count":12,"last_activity_at":"2023-06-05T12:37:02.000Z","accepted_answer_id":35612484},{"id":12144077,"link":"https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void","tags":["c#","asynchronous",".net-4.5"],"owner":"user981225","score":754,"title":"async/await - when to return a Task vs void?","created_at":"2012-08-27T14:33:39.000Z","view_count":665856,"is_answered":true,"answer_count":6,"last_activity_at":"2023-01-12T01:47:01.000Z","accepted_answer_id":12144426},{"id":12337671,"link":"https://stackoverflow.com/questions/12337671/using-async-await-for-multiple-tasks","tags":["c#",".net","task-parallel-library","async-await","c#-5.0"],"owner":"Ben Foster","score":548,"title":"Using async/await for multiple tasks","created_at":"2012-09-09T08:40:04.000Z","view_count":444967,"is_answered":true,"answer_count":8,"last_activity_at":"2024-04-24T13:20:30.000Z","accepted_answer_id":12338717},{"id":33289726,"link":"https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout","tags":["javascript","async-await","settimeout","ecmascript-2017"],"owner":"JShinigami","score":763,"title":"Combination of async function + await + setTimeout","created_at":"2015-10-22T20:04:42.000Z","view_count":1004285,"is_answered":true,"answer_count":19,"last_activity_at":"2024-06-25T00:41:36.000Z","accepted_answer_id":33292942},{"id":33527653,"link":"https://stackoverflow.com/questions/33527653/babel-6-regeneratorruntime-is-not-defined","tags":["javascript","node.js","babeljs"],"owner":"BrunoLM","score":829,"title":"Babel 6 regeneratorRuntime is not defined","created_at":"2015-11-04T16:58:28.000Z","view_count":778545,"is_answered":true,"answer_count":48,"last_activity_at":"2022-05-13T14:21:08.000Z","accepted_answer_id":33527883},{"id":40140149,"link":"https://stackoverflow.com/questions/40140149/use-async-await-with-array-map","tags":["javascript","typescript","promise","async-await","ecmascript-2017"],"owner":"Alon","score":614,"title":"Use async await with Array.map","created_at":"2016-10-19T19:39:06.000Z","view_count":629878,"is_answered":true,"answer_count":11,"last_activity_at":"2024-10-17T16:49:11.000Z","accepted_answer_id":40140562},{"id":34930735,"link":"https://stackoverflow.com/questions/34930735/pros-cons-of-using-redux-saga-with-es6-generators-vs-redux-thunk-with-es2017-asy","tags":["javascript","reactjs","redux","redux-thunk","redux-saga"],"owner":"hampusohlsson","score":581,"title":"Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await","created_at":"2016-01-21T17:45:12.000Z","view_count":137234,"is_answered":true,"answer_count":11,"last_activity_at":"2025-05-22T21:18:56.000Z","accepted_answer_id":34933395},{"id":5095183,"link":"https://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously","tags":["c#","asynchronous","c#-5.0","async-await"],"owner":"Rachel","score":775,"title":"How would I run an async Task&lt;T&gt; method synchronously?","created_at":"2011-02-23T18:18:27.000Z","view_count":579272,"is_answered":true,"answer_count":23,"last_activity_at":"2024-05-13T19:35:22.000Z","accepted_answer_id":5097066},{"id":9343594,"link":"https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c","tags":["c#","asynchronous","async-await","synchronous"],"owner":"Tower","score":1445,"title":"How to call asynchronous method from synchronous method in C#?","created_at":"2012-02-18T17:49:28.000Z","view_count":1442880,"is_answered":true,"answer_count":15,"last_activity_at":"2025-07-04T14:02:21.000Z","accepted_answer_id":9343733},{"id":50757497,"link":"https://stackoverflow.com/questions/50757497/simplest-async-await-example-possible-in-python","tags":["python","python-3.x","asynchronous","async-await","python-asyncio"],"owner":"Basj","score":302,"title":"Simplest async/await example possible in Python","created_at":"2018-06-08T09:28:03.000Z","view_count":438388,"is_answered":true,"answer_count":10,"last_activity_at":"2025-03-05T07:20:43.000Z","accepted_answer_id":53420574},{"id":42453683,"link":"https://stackoverflow.com/questions/42453683/how-to-reject-in-async-await-syntax","tags":["javascript","typescript","asynchronous","es6-promise","ecmascript-2017"],"owner":"Phoenix","score":499,"title":"How to reject in async/await syntax?","created_at":"2017-02-25T08:20:24.000Z","view_count":302371,"is_answered":true,"answer_count":8,"last_activity_at":"2024-06-10T09:01:29.000Z","accepted_answer_id":42453705},{"id":49432579,"link":"https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function","tags":["javascript","node.js"],"owner":"j.doe","score":377,"title":"await is only valid in async function","created_at":"2018-03-22T15:29:02.000Z","view_count":863309,"is_answered":true,"answer_count":15,"last_activity_at":"2024-09-09T20:08:12.000Z","accepted_answer_id":49432604},{"id":35011656,"link":"https://stackoverflow.com/questions/35011656/async-await-in-linq-select","tags":["c#","linq","asynchronous"],"owner":"Alexander Derck","score":373,"title":"Async await in linq select","created_at":"2016-01-26T10:26:08.000Z","view_count":368600,"is_answered":true,"answer_count":9,"last_activity_at":"2025-11-18T09:56:22.000Z","accepted_answer_id":35016869}],"quota_remaining":299},"meta":{"timestamp":"2026-05-30T06:33:30.443Z","request_id":"a2cc24d2-7cbd-41d6-a686-f2adc089cb62"},"status":"ok","message":"Search completed","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/user":{"get":{"operationId":"get_v1_user","tags":["Stack Exchange"],"summary":"A user profile by id","description":"","parameters":[{"name":"id","in":"query","required":true,"description":"Numeric user id","schema":{"type":"string"},"example":"22656"},{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"id":22656,"link":"https://stackoverflow.com/users/22656/jon-skeet","name":"Jon Skeet","badges":{"gold":895,"bronze":9357,"silver":9318},"location":"Reading, United Kingdom","user_type":"registered","created_at":"2008-09-26T12:05:05.000Z","reputation":1527510,"profile_image":"https://www.gravatar.com/avatar/6d8ebb117e8d83d74ea95fbdd0f87e13?s=256&d=identicon&r=PG","last_access_at":"2026-05-29T19:26:28.000Z"},"meta":{"timestamp":"2026-05-30T06:33:31.171Z","request_id":"71c132cc-8cd1-4db2-b206-cf8d80cff462"},"status":"ok","message":"User retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/answers":{"get":{"operationId":"get_v1_answers","tags":["Questions"],"summary":"Answers to a question, highest-voted first","description":"","parameters":[{"name":"id","in":"query","required":true,"description":"Numeric question id","schema":{"type":"string"},"example":"11227809"},{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"},{"name":"sort","in":"query","required":false,"description":"votes (default), activity or creation","schema":{"type":"string"},"example":"votes"},{"name":"limit","in":"query","required":false,"description":"Max results (1-30)","schema":{"type":"string"},"example":"10"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"site":"stackoverflow","sort":"votes","count":10,"results":[{"id":11227902,"body":"<p><strong>You are a victim of <a href=\"https://en.wikipedia.org/wiki/Branch_predictor\" rel=\"noreferrer\">branch prediction</a> fail.</strong></p>\n<hr />\n<h2>What is Branch Prediction?</h2>\n<p>Consider a railroad junction:</p>\n<p><a href=\"https://commons.wikimedia.org/wiki/File:Entroncamento_do_Transpraia.JPG\" rel=\"noreferrer\"><img src=\"https://i.sstatic.net/muxnt.jpg\" alt=\"Image showing a railroad junction\" /></a>\n<sub><a href=\"https://commons.wikimedia.org/wiki/File:Entroncamento_do_Transpraia.JPG\" rel=\"noreferrer\">Image</a> by Mecanismo, via Wikimedia Commons. Used under the <a href=\"https://creativecommons.org/licenses/by-sa/3.0/deed.en\" rel=\"noreferrer\">CC-By-SA 3.0</a> license.</sub></p>\n<p>Now for the sake of argument, suppose this is back in the 1800s - before long-distance or radio communication.</p>\n<p>You are a blind operator of a junction and you hear a train coming. You have no idea which way it is supposed to go. You stop the train to ask the driver which direction they want. And then you set the switch appropriately.</p>\n<p><em>Trains are heavy and have a lot of inertia, so they take forever to start up and slow down.</em></p>\n<p>Is there a better way? You guess which direction the train will go!</p>\n<ul>\n<li>If you guessed right, it continues on.</li>\n<li>If you guessed wrong, the driver will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.</li>\n</ul>\n<p><strong>If you guess right every time</strong>, the train will never have to stop.<br />\n<strong>If you guess wrong too often</strong>, the train will spend a lot of time stopping, backing up, and restarting.</p>\n<hr />\n<p><strong>Consider an if-statement:</strong> At the processor level, it is a branch instruction:</p>\n<p><img src=\"https://i.sstatic.net/pyfwC.png\" alt=\"if(x &gt;= 128) compiles into a jump-if-less-than processor instruction.\" /></p>\n<p>You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.</p>\n<p><em>Modern processors are complicated and have long pipelines. This means they take forever to &quot;warm up&quot; and &quot;slow down&quot;.</em></p>\n<p>Is there a better way? You guess which direction the branch will go!</p>\n<ul>\n<li>If you guessed right, you continue executing.</li>\n<li>If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.</li>\n</ul>\n<p><strong>If you guess right every time</strong>, the execution will never have to stop.<br />\n<strong>If you guess wrong too often</strong>, you spend a lot of time stalling, rolling back, and restarting.</p>\n<hr />\n<p>This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.</p>\n<p>How would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every three times, you guess the same...</p>\n<p><em><strong>In other words, you try to identify a pattern and follow it.</strong></em> This is more or less how branch predictors work.</p>\n<p>Most applications have well-behaved branches. Therefore, modern branch predictors will typically achieve &gt;90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.</p>\n<p>Further reading: <a href=\"https://en.wikipedia.org/wiki/Branch_predictor\" rel=\"noreferrer\">&quot;Branch predictor&quot; article on Wikipedia</a>.</p>\n<hr />\n<h2>As hinted from above, the culprit is this if-statement:</h2>\n<pre><code>if (data[c] &gt;= 128)\n    sum += data[c];\n</code></pre>\n<p>Notice that the data is evenly distributed between 0 and 255. When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.</p>\n<p>This is very friendly to the branch predictor since the branch consecutively goes the same direction many times. Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.</p>\n<p><strong>Quick visualization:</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>T = branch taken\nN = branch not taken\n\ndata[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...\nbranch = N  N  N  N  N  ...   N    N    T    T    T  ...   T    T    T  ...\n\n       = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT  (easy to predict)\n</code></pre>\n<p>However, when the data is completely random, the branch predictor is rendered useless, because it can't predict random data. Thus there will probably be around 50% misprediction (no better than random guessing).</p>\n<pre class=\"lang-none prettyprint-override\"><code>data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, ...\nbranch =   T,   T,   N,   T,   T,   T,   T,  N,   T,   N,   N,   T,   T,   T  ...\n\n       = TTNTTTTNTNNTTT ...   (completely random - impossible to predict)\n</code></pre>\n<hr />\n<p><strong>What can be done?</strong></p>\n<p>If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.</p>\n<p>Replace:</p>\n<pre><code>if (data[c] &gt;= 128)\n    sum += data[c];\n</code></pre>\n<p>with:</p>\n<pre><code>int t = (data[c] - 128) &gt;&gt; 31;\nsum += ~t &amp; data[c];\n</code></pre>\n<p>This eliminates the branch and replaces it with some bitwise operations.</p>\n<p><sub>(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of <code>data[]</code>.)</sub></p>\n<p><strong>Benchmarks: Core i7 920 @ 3.5 GHz</strong></p>\n<p>C++ - Visual Studio 2010 - x64 Release</p>\n<div class=\"s-table-container\"><table class=\"s-table\">\n<thead>\n<tr>\n<th>Scenario</th>\n<th>Time (seconds)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Branching - Random data</td>\n<td>11.777</td>\n</tr>\n<tr>\n<td>Branching - Sorted data</td>\n<td>2.352</td>\n</tr>\n<tr>\n<td>Branchless - Random data</td>\n<td>2.564</td>\n</tr>\n<tr>\n<td>Branchless - Sorted data</td>\n<td>2.587</td>\n</tr>\n</tbody>\n</table></div>\n<p>Java - NetBeans 7.1.1 JDK 7 - x64</p>\n<div class=\"s-table-container\"><table class=\"s-table\">\n<thead>\n<tr>\n<th>Scenario</th>\n<th>Time (seconds)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Branching - Random data</td>\n<td>10.93293813</td>\n</tr>\n<tr>\n<td>Branching - Sorted data</td>\n<td>5.643797077</td>\n</tr>\n<tr>\n<td>Branchless - Random data</td>\n<td>3.113581453</td>\n</tr>\n<tr>\n<td>Branchless - Sorted data</td>\n<td>3.186068823</td>\n</tr>\n</tbody>\n</table></div>\n<p>Observations:</p>\n<ul>\n<li><strong>With the Branch:</strong> There is a huge difference between the sorted and unsorted data.</li>\n<li><strong>With the Hack:</strong> There is no difference between sorted and unsorted data.</li>\n<li>In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.</li>\n</ul>\n<p>A general rule of thumb is to avoid data-dependent branching in critical loops (such as in this example).</p>\n<hr />\n<p><strong>Update:</strong></p>\n<ul>\n<li><p>GCC 4.6.1 with <code>-O3</code> or <code>-ftree-vectorize</code> on x64 is able to generate a conditional move, so there is no difference between the sorted and unsorted data - both are fast.  This is called &quot;if-conversion&quot; (to branchless) and is necessary for vectorization but also sometimes good for scalar.</p>\n<p>(Or somewhat fast: for the already-sorted case, <code>cmov</code> can be slower especially if GCC puts it on the critical path instead of just <code>add</code>, especially on Intel before Broadwell where <code>cmov</code> has 2-cycle latency: <em><a href=\"https://stackoverflow.com/questions/28875325/gcc-optimization-flag-o3-makes-code-slower-than-o2\">gcc optimization flag -O3 makes code slower than -O2</a></em>)</p>\n</li>\n<li><p>VC++ 2010 is unable to generate conditional moves for this branch even under <code>/Ox</code>.</p>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Intel_C++_Compiler\" rel=\"noreferrer\">Intel C++ Compiler</a> (ICC) 11 does something miraculous. It <a href=\"https://en.wikipedia.org/wiki/Loop_interchange\" rel=\"noreferrer\">interchanges the two loops</a>, thereby hoisting the unpredictable branch to the outer loop. Not only is it immune to the mispredictions, it's also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...</p>\n</li>\n<li><p>If you give the Intel compiler the branchless code, it just outright vectorizes it... and is just as fast as with the branch (with the loop interchange).</p>\n</li>\n</ul>\n<ul>\n<li>Clang also vectorizes the <code>if()</code> version, as will GCC 5 and later with <code>-O3</code>, even though it takes quite a few instructions to sign-extend to the 64-bit sum on x86 without SSE4 or AVX2.  (<code>-march=x86-64-v2</code> or <code>v3</code>).  See <em><a href=\"https://stackoverflow.com/questions/66521344/why-is-processing-an-unsorted-array-the-same-speed-as-processing-a-sorted-array\">Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?</a></em></li>\n</ul>\n<p>This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...</p>\n","owner":"Mysticial","score":35287,"created_at":"2012-06-27T13:56:42.000Z","is_accepted":true,"question_id":11227809,"last_activity_at":"2024-03-04T17:37:13.000Z"},{"id":11227877,"body":"<p><strong>Branch prediction.</strong></p>\n<p>With a sorted array, the condition <code>data[c] &gt;= 128</code> is first <code>false</code> for a streak of values, then becomes <code>true</code> for all later values. That's easy to predict. With an unsorted array, you pay for the branching cost.</p>\n","owner":"Daniel Fischer","score":4768,"created_at":"2012-06-27T13:54:45.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2016-08-05T07:53:10.000Z"},{"id":11237235,"body":"<p>The reason why performance improves drastically when the data is sorted is that the branch prediction penalty is removed, as explained beautifully in <a href=\"//stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array/11227902#11227902\">Mysticial's answer</a>.</p>\n<p>Now, if we look at the code</p>\n<pre><code>if (data[c] &gt;= 128)\n    sum += data[c];\n</code></pre>\n<p>we can find that the meaning of this particular <code>if... else...</code> branch is to add something when a condition is satisfied. This type of branch can be easily transformed into a <strong>conditional move</strong> statement, which would be compiled into a conditional move instruction: <code>cmovl</code>, in an <code>x86</code> system. The branch and thus the potential branch prediction penalty is removed.</p>\n<p>In <code>C</code>, thus <code>C++</code>, the statement, which would compile directly (without any optimization) into the conditional move instruction in <code>x86</code>, is the ternary operator <code>... ? ... : ...</code>. So we rewrite the above statement into an equivalent one:</p>\n<pre><code>sum += data[c] &gt;=128 ? data[c] : 0;\n</code></pre>\n<p>While maintaining readability, we can check the speedup factor.</p>\n<p>On an Intel <a href=\"//en.wikipedia.org/wiki/Intel_Core#Core_i7\" rel=\"noreferrer\">Core i7</a>-2600K @ 3.4 GHz and Visual Studio 2010 Release Mode, the benchmark is:</p>\n<p><strong>x86</strong></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Scenario</th>\n<th>Time (seconds)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Branching - Random data</td>\n<td>8.885</td>\n</tr>\n<tr>\n<td>Branching - Sorted data</td>\n<td>1.528</td>\n</tr>\n<tr>\n<td>Branchless - Random data</td>\n<td>3.716</td>\n</tr>\n<tr>\n<td>Branchless - Sorted data</td>\n<td>3.71</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><strong>x64</strong></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Scenario</th>\n<th>Time (seconds)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Branching - Random data</td>\n<td>11.302</td>\n</tr>\n<tr>\n<td>Branching - Sorted data</td>\n<td>1.830</td>\n</tr>\n<tr>\n<td>Branchless - Random data</td>\n<td>2.736</td>\n</tr>\n<tr>\n<td>Branchless - Sorted data</td>\n<td>2.737</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The result is robust in multiple tests. We get a great speedup when the branch result is unpredictable, but we suffer a little bit when it is predictable. In fact, when using a conditional move, the performance is the same regardless of the data pattern.</p>\n<p>Now let's look more closely by investigating the <code>x86</code> assembly they generate. For simplicity, we use two functions <code>max1</code> and <code>max2</code>.</p>\n<p><code>max1</code> uses the conditional branch <code>if... else ...</code>:</p>\n<pre><code>int max1(int a, int b) {\n    if (a &gt; b)\n        return a;\n    else\n        return b;\n}\n</code></pre>\n<p><code>max2</code> uses the ternary operator <code>... ? ... : ...</code>:</p>\n<pre><code>int max2(int a, int b) {\n    return a &gt; b ? a : b;\n}\n</code></pre>\n<p>On an x86-64 machine, <code>GCC -S</code> generates the assembly below.</p>\n<pre><code>:max1\n    movl    %edi, -4(%rbp)\n    movl    %esi, -8(%rbp)\n    movl    -4(%rbp), %eax\n    cmpl    -8(%rbp), %eax\n    jle     .L2\n    movl    -4(%rbp), %eax\n    movl    %eax, -12(%rbp)\n    jmp     .L4\n.L2:\n    movl    -8(%rbp), %eax\n    movl    %eax, -12(%rbp)\n.L4:\n    movl    -12(%rbp), %eax\n    leave\n    ret\n\n:max2\n    movl    %edi, -4(%rbp)\n    movl    %esi, -8(%rbp)\n    movl    -4(%rbp), %eax\n    cmpl    %eax, -8(%rbp)\n    cmovge  -8(%rbp), %eax\n    leave\n    ret\n</code></pre>\n<p><code>max2</code> uses much less code due to the usage of instruction <code>cmovge</code>. But the real gain is that <code>max2</code> does not involve branch jumps, <code>jmp</code>, which would have a significant performance penalty if the predicted result is not right.</p>\n<p>So why does a conditional move perform better?</p>\n<p>In a typical <code>x86</code> processor, the execution of an instruction is divided into several stages. Roughly, we have different hardware to deal with different stages. So we do not have to wait for one instruction to finish to start a new one. This is called <strong><a href=\"//en.wikipedia.org/wiki/Pipeline_(computing)\" rel=\"noreferrer\">pipelining</a></strong>.</p>\n<p>In a branch case, the following instruction is determined by the preceding one, so we cannot do pipelining. We have to either wait or predict.</p>\n<p>In a conditional move case, the execution of conditional move instruction is divided into several stages, but the earlier stages like <code>Fetch</code> and <code>Decode</code> do not depend on the result of the previous instruction; only the latter stages need the result. Thus, we wait a fraction of one instruction's execution time. This is why the conditional move version is slower than the branch when the prediction is easy.</p>\n<p>The book <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0136108040\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Computer Systems: A Programmer's Perspective, second edition</a></em> explains this in detail. You can check Section 3.6.6 for <em>Conditional Move Instructions</em>, entire Chapter 4 for <em>Processor Architecture</em>, and Section 5.11.2 for special treatment for <em>Branch Prediction and Misprediction Penalties</em>.</p>\n<p>Sometimes, some modern compilers can optimize our code to assembly with better performance, and sometimes some compilers can't (the code in question is using Visual Studio's native compiler). Knowing the performance difference between a branch and a conditional move when unpredictable can help us write code with better performance when the scenario gets so complex that the compiler can not optimize them automatically.</p>\n","owner":"WiSaGaN","score":3860,"created_at":"2012-06-28T02:14:03.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2022-07-03T15:12:52.000Z"},{"id":11303693,"body":"<p>If you are curious about even more optimizations that can be done to this code, consider this:</p>\n<p>Starting with the original loop:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (unsigned i = 0; i &lt; 100000; ++i)\n{\n    for (unsigned j = 0; j &lt; arraySize; ++j)\n    {\n        if (data[j] &gt;= 128)\n            sum += data[j];\n    }\n}\n</code></pre>\n<p>With loop interchange, we can safely change this loop to:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (unsigned j = 0; j &lt; arraySize; ++j)\n{\n    for (unsigned i = 0; i &lt; 100000; ++i)\n    {\n        if (data[j] &gt;= 128)\n            sum += data[j];\n    }\n}\n</code></pre>\n<p>Then, you can see that the <code>if</code> conditional is constant throughout the execution of the <code>i</code> loop, so you can hoist the <code>if</code> out:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> for (unsigned j = 0; j &lt; arraySize; ++j)\n {\n     if (data[j] &gt;= 128)\n     {\n         for (unsigned i = 0; i &lt; 100000; ++i)\n         {\n             sum += data[j];\n         }\n    }\n}\n</code></pre>\n<p>Then, you see that the inner loop can be collapsed into one single expression, assuming the floating point model allows it (<code>/fp:fast</code> is thrown, for example)</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (unsigned j = 0; j &lt; arraySize; ++j)\n{\n    if (data[j] &gt;= 128)\n    {\n        sum += data[j] * 100000;\n    }\n}\n</code></pre>\n<p>That one is 100,000 times faster than before.</p>\n","owner":"vulcan raven","score":2669,"created_at":"2012-07-03T02:25:30.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2024-01-02T18:32:46.000Z"},{"id":12853037,"body":"<p>No doubt some of us would be interested in ways of identifying code that is problematic for the CPU's branch-predictor. The Valgrind tool <code>cachegrind</code> has a branch-predictor simulator, enabled by using the <code>--branch-sim=yes</code> flag. Running it over the examples in this question, with the number of outer loops reduced to 10000 and compiled with <code>g++</code>, gives these results:</p>\n\n<p><strong>Sorted:</strong></p>\n\n<pre><code>==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)\n==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)\n==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )\n</code></pre>\n\n<p><strong>Unsorted:</strong></p>\n\n<pre><code>==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)\n==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)\n==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )\n</code></pre>\n\n<p>Drilling down into the line-by-line output produced by <code>cg_annotate</code> we see for the loop in question:</p>\n\n<p><strong>Sorted:</strong></p>\n\n<pre><code>          Bc    Bcm Bi Bim\n      10,001      4  0   0      for (unsigned i = 0; i &lt; 10000; ++i)\n           .      .  .   .      {\n           .      .  .   .          // primary loop\n 327,690,000 10,016  0   0          for (unsigned c = 0; c &lt; arraySize; ++c)\n           .      .  .   .          {\n 327,680,000 10,006  0   0              if (data[c] &gt;= 128)\n           0      0  0   0                  sum += data[c];\n           .      .  .   .          }\n           .      .  .   .      }\n</code></pre>\n\n<p><strong>Unsorted:</strong></p>\n\n<pre><code>          Bc         Bcm Bi Bim\n      10,001           4  0   0      for (unsigned i = 0; i &lt; 10000; ++i)\n           .           .  .   .      {\n           .           .  .   .          // primary loop\n 327,690,000      10,038  0   0          for (unsigned c = 0; c &lt; arraySize; ++c)\n           .           .  .   .          {\n 327,680,000 164,050,007  0   0              if (data[c] &gt;= 128)\n           0           0  0   0                  sum += data[c];\n           .           .  .   .          }\n           .           .  .   .      }\n</code></pre>\n\n<p>This lets you easily identify the problematic line - in the unsorted version the <code>if (data[c] &gt;= 128)</code> line is causing 164,050,007 mispredicted conditional branches (<code>Bcm</code>) under cachegrind's branch-predictor model, whereas it's only causing 10,006 in the sorted version.</p>\n\n<hr>\n\n<p>Alternatively, on Linux you can use the performance counters subsystem to accomplish the same task, but with native performance using CPU counters.</p>\n\n<pre><code>perf stat ./sumtest_sorted\n</code></pre>\n\n<p><strong>Sorted:</strong></p>\n\n<pre><code> Performance counter stats for './sumtest_sorted':\n\n  11808.095776 task-clock                #    0.998 CPUs utilized          \n         1,062 context-switches          #    0.090 K/sec                  \n            14 CPU-migrations            #    0.001 K/sec                  \n           337 page-faults               #    0.029 K/sec                  \n26,487,882,764 cycles                    #    2.243 GHz                    \n41,025,654,322 instructions              #    1.55  insns per cycle        \n 6,558,871,379 branches                  #  555.455 M/sec                  \n       567,204 branch-misses             #    0.01% of all branches        \n\n  11.827228330 seconds time elapsed\n</code></pre>\n\n<p><strong>Unsorted:</strong></p>\n\n<pre><code> Performance counter stats for './sumtest_unsorted':\n\n  28877.954344 task-clock                #    0.998 CPUs utilized          \n         2,584 context-switches          #    0.089 K/sec                  \n            18 CPU-migrations            #    0.001 K/sec                  \n           335 page-faults               #    0.012 K/sec                  \n65,076,127,595 cycles                    #    2.253 GHz                    \n41,032,528,741 instructions              #    0.63  insns per cycle        \n 6,560,579,013 branches                  #  227.183 M/sec                  \n 1,646,394,749 branch-misses             #   25.10% of all branches        \n\n  28.935500947 seconds time elapsed\n</code></pre>\n\n<p>It can also do source code annotation with dissassembly.</p>\n\n<pre><code>perf record -e branch-misses ./sumtest_unsorted\nperf annotate -d sumtest_unsorted\n</code></pre>\n\n\n\n<pre><code> Percent |      Source code &amp; Disassembly of sumtest_unsorted\n------------------------------------------------\n...\n         :                      sum += data[c];\n    0.00 :        400a1a:       mov    -0x14(%rbp),%eax\n   39.97 :        400a1d:       mov    %eax,%eax\n    5.31 :        400a1f:       mov    -0x20040(%rbp,%rax,4),%eax\n    4.60 :        400a26:       cltq   \n    0.00 :        400a28:       add    %rax,-0x30(%rbp)\n...\n</code></pre>\n\n<p>See <a href=\"https://perf.wiki.kernel.org/index.php/Tutorial\" rel=\"noreferrer\">the performance tutorial</a> for more details.</p>\n","owner":"caf","score":2213,"created_at":"2012-10-12T05:53:33.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2012-10-18T19:20:21.000Z"},{"id":16184827,"body":"<p>I just read up on this question and its answers, and I feel an answer is missing.</p>\n\n<p>A common way to eliminate branch prediction that I've found to work particularly good in managed languages is a table lookup instead of using a branch (although I haven't tested it in this case).</p>\n\n<p>This approach works in general if:</p>\n\n<ol>\n<li>it's a small table and is likely to be cached in the processor, and</li>\n<li>you are running things in a quite tight loop and/or the processor can preload the data.</li>\n</ol>\n\n<p><strong>Background and why</strong></p>\n\n<p>From a processor perspective, your memory is slow. To compensate for the difference in speed, a couple of caches are built into your processor (L1/L2 cache). So imagine that you're doing your nice calculations and figure out that you need a piece of memory. The processor will get its 'load' operation and loads the piece of memory into cache -- and then uses the cache to do the rest of the calculations. Because memory is relatively slow, this 'load' will slow down your program.</p>\n\n<p>Like branch prediction, this was optimized in the Pentium processors: the processor predicts that it needs to load a piece of data and attempts to load that into the cache before the operation actually hits the cache. As we've already seen, branch prediction sometimes goes horribly wrong -- in the worst case scenario you need to go back and actually wait for a memory load, which will take forever (<strong>in other words: failing branch prediction is bad, a memory load after a branch prediction fail is just horrible!</strong>).</p>\n\n<p>Fortunately for us, if the memory access pattern is predictable, the processor will load it in its fast cache and all is well.</p>\n\n<p>The first thing we need to know is what is <em>small</em>? While smaller is generally better, a rule of thumb is to stick to lookup tables that are &lt;= 4096 bytes in size. As an upper limit: if your lookup table is larger than 64K it's probably worth reconsidering.</p>\n\n<p><strong>Constructing a table</strong></p>\n\n<p>So we've figured out that we can create a small table. Next thing to do is get a lookup function in place. Lookup functions are usually small functions that use a couple of basic integer operations (and, or, xor, shift, add, remove and perhaps multiply). You want to have your input translated by the lookup function to some kind of 'unique key' in your table, which then simply gives you the answer of all the work you wanted it to do.</p>\n\n<p>In this case: >= 128 means we can keep the value, &lt; 128 means we get rid of it. The easiest way to do that is by using an 'AND': if we keep it, we AND it with 7FFFFFFF; if we want to get rid of it, we AND it with 0. Notice also that 128 is a power of 2 -- so we can go ahead and make a table of 32768/128 integers and fill it with one zero and a lot of 7FFFFFFFF's.</p>\n\n<p><strong>Managed languages</strong></p>\n\n<p>You might wonder why this works well in managed languages. After all, managed languages check the boundaries of the arrays with a branch to ensure you don't mess up...</p>\n\n<p>Well, not exactly... :-)</p>\n\n<p>There has been quite some work on eliminating this branch for managed languages. For example:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>for (int i = 0; i &lt; array.Length; ++i)\n{\n   // Use array[i]\n}\n</code></pre>\n\n<p>In this case, it's obvious to the compiler that the boundary condition will never be hit. At least the Microsoft JIT compiler (but I expect Java does similar things) will notice this and remove the check altogether. WOW, that means no branch. Similarly, it will deal with other obvious cases.</p>\n\n<p>If you run into trouble with lookups in managed languages -- the key is to add a <code>&amp; 0x[something]FFF</code> to your lookup function to make the boundary check predictable -- and watch it going faster.</p>\n\n<p><strong>The result of this case</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// Generate data\nint arraySize = 32768;\nint[] data = new int[arraySize];\n\nRandom random = new Random(0);\nfor (int c = 0; c &lt; arraySize; ++c)\n{\n    data[c] = random.Next(256);\n}\n\n/*To keep the spirit of the code intact, I'll make a separate lookup table\n(I assume we cannot modify 'data' or the number of loops)*/\n\nint[] lookup = new int[256];\n\nfor (int c = 0; c &lt; 256; ++c)\n{\n    lookup[c] = (c &gt;= 128) ? c : 0;\n}\n\n// Test\nDateTime startTime = System.DateTime.Now;\nlong sum = 0;\n\nfor (int i = 0; i &lt; 100000; ++i)\n{\n    // Primary loop\n    for (int j = 0; j &lt; arraySize; ++j)\n    {\n        /* Here you basically want to use simple operations - so no\n        random branches, but things like &amp;, |, *, -, +, etc. are fine. */\n        sum += lookup[data[j]];\n    }\n}\n\nDateTime endTime = System.DateTime.Now;\nConsole.WriteLine(endTime - startTime);\nConsole.WriteLine(\"sum = \" + sum);\nConsole.ReadLine();\n</code></pre>\n","owner":"atlaste","score":1632,"created_at":"2013-04-24T06:26:28.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2019-01-16T04:47:21.000Z"},{"id":14889969,"body":"<p>As data is distributed between 0 and 255 when the array is sorted, around the first half of the iterations will not enter the <code>if</code>-statement (the <code>if</code> statement is shared below).</p>\n\n<pre><code>if (data[c] &gt;= 128)\n    sum += data[c];\n</code></pre>\n\n<p>The question is: What makes the above statement not execute in certain cases as in case of sorted data? Here comes the \"branch predictor\". A branch predictor is a digital circuit that tries to guess which way a branch (e.g. an <code>if-then-else</code> structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance!</p>\n\n<p><strong>Let's do some bench marking to understand it better</strong></p>\n\n<p>The performance of an <code>if</code>-statement depends on whether its condition has a predictable pattern. If the condition is always true or always false, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the pattern is unpredictable, the <code>if</code>-statement will be much more expensive.</p>\n\n<p>Let’s measure the performance of this loop with different conditions:</p>\n\n<pre><code>for (int i = 0; i &lt; max; i++)\n    if (condition)\n        sum++;\n</code></pre>\n\n<p>Here are the timings of the loop with different true-false patterns:</p>\n\n<pre><code>Condition                Pattern             Time (ms)\n-------------------------------------------------------\n(i &amp; 0×80000000) == 0    T repeated          322\n\n(i &amp; 0xffffffff) == 0    F repeated          276\n\n(i &amp; 1) == 0             TF alternating      760\n\n(i &amp; 3) == 0             TFFFTFFF…           513\n\n(i &amp; 2) == 0             TTFFTTFF…           1675\n\n(i &amp; 4) == 0             TTTTFFFFTTTTFFFF…   1275\n\n(i &amp; 8) == 0             8T 8F 8T 8F …       752\n\n(i &amp; 16) == 0            16T 16F 16T 16F …   490\n</code></pre>\n\n<p>A “<strong>bad</strong>” true-false pattern can make an <code>if</code>-statement up to six times slower than a “<strong>good</strong>” pattern! Of course, which pattern is good and which is bad depends on the exact instructions generated by the compiler and on the specific processor.</p>\n\n<p>So there is no doubt about the impact of branch prediction on performance!</p>\n","owner":"Saqlain","score":1453,"created_at":"2013-02-15T07:24:16.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2019-02-27T10:58:32.000Z"},{"id":17782979,"body":"<p>One way to avoid branch prediction errors is to build a lookup table, and index it using the data.  Stefan de Bruijn discussed that in his answer.</p>\n<p>But in this case, we know values are in the range [0, 255] and we only care about values &gt;= 128.  That means we can easily extract a single bit that will tell us whether we want a value or not: by shifting the data to the right 7 bits, we are left with a 0 bit or a 1 bit, and we only want to add the value when we have a 1 bit.  Let's call this bit the &quot;decision bit&quot;.</p>\n<p>By using the 0/1 value of the decision bit as an index into an array, we can make code that will be equally fast whether the data is sorted or not sorted.  Our code will always add a value, but when the decision bit is 0, we will add the value somewhere we don't care about.  Here's the code:</p>\n<pre><code>// Test\nclock_t start = clock();\nlong long a[] = {0, 0};\nlong long sum;\n\nfor (unsigned i = 0; i &lt; 100000; ++i)\n{\n    // Primary loop\n    for (unsigned c = 0; c &lt; arraySize; ++c)\n    {\n        int j = (data[c] &gt;&gt; 7);\n        a[j] += data[c];\n    }\n}\n\ndouble elapsedTime = static_cast&lt;double&gt;(clock() - start) / CLOCKS_PER_SEC;\nsum = a[1];\n</code></pre>\n<p>This code wastes half of the adds but never has a branch prediction failure.  It's tremendously faster on random data than the version with an actual if statement.</p>\n<p>But in my testing, an explicit lookup table was slightly faster than this, probably because indexing into a lookup table was slightly faster than bit shifting.  This shows how my code sets up and uses the lookup table (unimaginatively called <code>lut</code> for &quot;LookUp Table&quot; in the code).  Here's the C++ code:</p>\n<pre><code>// Declare and then fill in the lookup table\nint lut[256];\nfor (unsigned c = 0; c &lt; 256; ++c)\n    lut[c] = (c &gt;= 128) ? c : 0;\n\n// Use the lookup table after it is built\nfor (unsigned i = 0; i &lt; 100000; ++i)\n{\n    // Primary loop\n    for (unsigned c = 0; c &lt; arraySize; ++c)\n    {\n        sum += lut[data[c]];\n    }\n}\n</code></pre>\n<p>In this case, the lookup table was only 256 bytes, so it fits nicely in a cache and all was fast.  This technique wouldn't work well if the data was 24-bit values and we only wanted half of them... the lookup table would be far too big to be practical.  On the other hand, we can combine the two techniques shown above: first shift the bits over, then index a lookup table.  For a 24-bit value that we only want the top half value, we could potentially shift the data right by 12 bits, and be left with a 12-bit value for a table index.  A 12-bit table index implies a table of 4096 values, which might be practical.</p>\n<p>The technique of indexing into an array, instead of using an <code>if</code> statement, can be used for deciding which pointer to use.  I saw a library that implemented binary trees, and instead of having two named pointers (<code>pLeft</code> and <code>pRight</code> or whatever) had a length-2 array of pointers and used the &quot;decision bit&quot; technique to decide which one to follow.  For example, instead of:</p>\n<pre><code>if (x &lt; node-&gt;value)\n    node = node-&gt;pLeft;\nelse\n    node = node-&gt;pRight;\n</code></pre>\n<p>this library would do something like:</p>\n<pre><code>i = (x &lt; node-&gt;value);\nnode = node-&gt;link[i];\n</code></pre>\n<p>Here's a link to this code: <a href=\"https://web.archive.org/web/20190207151651/https://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx\" rel=\"noreferrer\">Red Black Trees</a>, <em>Eternally Confuzzled</em></p>\n","owner":"steveha","score":1388,"created_at":"2013-07-22T08:29:30.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2021-01-27T10:03:36.000Z"},{"id":17828251,"body":"<p>In the sorted case, you can do better than relying on successful branch prediction or any branchless comparison trick: completely remove the branch.</p>\n\n<p>Indeed, the array is partitioned in a contiguous zone with <code>data &lt; 128</code> and another with <code>data &gt;= 128</code>. So you should find the partition point with a <a href=\"https://en.wikipedia.org/wiki/Dichotomic_search\" rel=\"noreferrer\">dichotomic search</a> (using <code>Lg(arraySize) = 15</code> comparisons), then do a straight accumulation from that point.</p>\n\n<p>Something like (unchecked)</p>\n\n<pre><code>int i= 0, j, k= arraySize;\nwhile (i &lt; k)\n{\n  j= (i + k) &gt;&gt; 1;\n  if (data[j] &gt;= 128)\n    k= j;\n  else\n    i= j;\n}\nsum= 0;\nfor (; i &lt; arraySize; i++)\n  sum+= data[i];\n</code></pre>\n\n<p>or, slightly more obfuscated</p>\n\n<pre><code>int i, k, j= (i + k) &gt;&gt; 1;\nfor (i= 0, k= arraySize; i &lt; k; (data[j] &gt;= 128 ? k : i)= j)\n  j= (i + k) &gt;&gt; 1;\nfor (sum= 0; i &lt; arraySize; i++)\n  sum+= data[i];\n</code></pre>\n\n<p>A yet faster approach, that gives an <strong>approximate</strong> solution for both sorted or unsorted is: <code>sum= 3137536;</code> (assuming a truly uniform distribution, 16384 samples with expected value 191.5) <strong>:-)</strong></p>\n","owner":"user1196549","score":1245,"created_at":"2013-07-24T07:57:39.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2019-05-11T11:31:12.000Z"},{"id":31210295,"body":"<p>The above behavior is happening because of Branch prediction.</p>\n<p>To understand branch prediction one must first understand an <strong>Instruction Pipeline.</strong></p>\n<p>The the steps of running an instruction can be overlapped with the sequence of steps of running the previous and next instruction, so that different steps can be executed concurrently in parallel. This technique is known as instruction pipelining and is used to increase throughput in modern processors. To understand this better please see this <a href=\"https://en.wikipedia.org/wiki/Pipeline_(computing)#Concept_and_motivation\" rel=\"noreferrer\">example on Wikipedia</a>.</p>\n<p>Generally, modern processors have quite long (and wide) pipelines, so many instruction can be in flight.  See <a href=\"https://www.lighterra.com/papers/modernmicroprocessors/\" rel=\"noreferrer\">Modern Microprocessors\nA 90-Minute Guide!</a> which starts by introducing basic in-order pipelining and goes from there.</p>\n<p>But for ease <strong>let's consider a simple in-order pipeline with these 4 steps only.</strong><br />\n(Like a <a href=\"https://en.wikipedia.org/wiki/Classic_RISC_pipeline\" rel=\"noreferrer\">classic 5-stage RISC</a>, but omitting a separate MEM stage.)</p>\n<ol>\n<li>IF -- Fetch the instruction from memory</li>\n<li>ID -- Decode the instruction</li>\n<li>EX -- Execute the instruction</li>\n<li>WB -- Write back to CPU register</li>\n</ol>\n<p><strong>4-stage pipeline in general for 2 instructions.</strong><br />\n<img src=\"https://i.sstatic.net/PqBBR.png\" alt=\"4-stage pipeline in general\" /></p>\n<p>Moving back to the above question let's consider the following instructions:</p>\n<pre><code>                        A) if (data[c] &gt;= 128)\n                                /\\\n                               /  \\\n                              /    \\\n                        true /      \\ false\n                            /        \\\n                           /          \\\n                          /            \\\n                         /              \\\n              B) sum += data[c];          C) for loop or print().\n</code></pre>\n<p>Without branch prediction, the following would occur:</p>\n<p>To execute instruction B or instruction C the processor will have to wait (<em>stall</em>) till the instruction A leaves the EX stage in the pipeline, as the decision to go to instruction B or instruction C depends on the result of instruction A.  (i.e. where to fetch from next.) So the pipeline will look like this:</p>\n<p><em><strong>Without prediction: when <code>if</code> condition is true:</strong></em>\n<img src=\"https://i.sstatic.net/0H4gP.png\" alt=\"enter image description here\" /></p>\n<p><em><strong>Without prediction: When <code>if</code> condition is false:</strong></em>\n<img src=\"https://i.sstatic.net/APpca.png\" alt=\"enter image description here\" /></p>\n<p>As a result of waiting for the result of instruction A, the total CPU cycles spent in the above case (without branch prediction; for both true and false) is 7.</p>\n<p><strong>So what is branch prediction?</strong></p>\n<p>Branch predictor will try to guess which way a branch (an if-then-else structure) will go before this is known for sure. It will not wait for the instruction A to reach the EX stage of the pipeline, but it will guess the decision and go to that instruction (B or C in case of our example).</p>\n<p><em><strong>In case of a correct guess, the pipeline looks something like this:</strong></em>\n<img src=\"https://i.sstatic.net/ZYUbs.png\" alt=\"enter image description here\" /></p>\n<p>If it is later detected that the guess was wrong then the partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay.\nThe time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good <a href=\"https://en.wikipedia.org/wiki/Branch_predictor\" rel=\"noreferrer\">branch predictor</a>.</p>\n<p>In the OP's code, the first time when the conditional, the branch predictor does not have any information to base up prediction, so the first time it will randomly choose the next instruction. (Or fall back to <em>static</em> prediction, typically forward not-taken, backward taken).  Later in the for loop, it can base the prediction on the history.\nFor an array sorted in ascending order, there are three possibilities:</p>\n<ol>\n<li> All the elements are less than 128\n<li> All the elements are greater than 128\n<li> Some starting new elements are less than 128 and later it become greater than 128\n</ol>\n<p>Let us assume that the predictor will always assume the true branch on the first run.</p>\n<p>So in the first case, it will always take the true branch since historically all its predictions are correct.\nIn the 2nd case, initially it will predict wrong, but after a few iterations, it will predict correctly.\nIn the 3rd case, it will initially predict correctly till the elements are less than 128. After which it will fail for some time and the correct itself when it sees branch prediction failure in history.</p>\n<p>In all these cases the failure will be too less in number and as a result, only a few times it will need to discard the partially executed instructions and start over with the correct branch, resulting in fewer CPU cycles.</p>\n<p>But in case of a random unsorted array, the prediction will need to discard the partially executed instructions and start over with the correct branch most of the time and result in more CPU cycles compared to the sorted array.</p>\n<hr />\n<p>Further reading:</p>\n<ul>\n<li><a href=\"https://www.lighterra.com/papers/modernmicroprocessors/\" rel=\"noreferrer\">Modern Microprocessors\nA 90-Minute Guide!</a></li>\n<li><a href=\"https://danluu.com/branch-prediction/\" rel=\"noreferrer\">Dan Luu's article on branch prediction</a> (which covers older branch predictors, not modern IT-TAGE or Perceptron)</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Branch_predictor\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Branch_predictor</a></li>\n<li><a href=\"https://hal.inria.fr/hal-01100647/document\" rel=\"noreferrer\">Branch Prediction and the Performance of Interpreters -\nDon’t Trust Folklore</a> - 2015 paper showing how well Intel's Haswell does at predicting the indirect branch of a Python interpreter's main loop (historically problematic due to a non-simple pattern), vs. earlier CPUs which didn't use IT-TAGE.  (They don't help with this fully random case, though.  Still 50% mispredict rate for the if inside the loop on a Skylake CPU when the source is compiled to branch asm.)</li>\n<li><a href=\"https://xania.org/201602/bpu-part-one\" rel=\"noreferrer\">Static branch prediction on newer Intel processors</a> - what CPUs actually do when running a branch instruction that doesn't have a dynamic prediction available.  Historically, forward not-taken (like an <code>if</code> or <code>break</code>), backward taken (like a loop) has been used because it's better than nothing.  Laying out code so the fast path / common case minimizes taken branches is good for I-cache density as well as static prediction, so compilers already do that.  (That's the <a href=\"https://stackoverflow.com/questions/1851299/is-it-possible-to-tell-the-branch-predictor-how-likely-it-is-to-follow-the-branc\">real effect</a> of <code>likely</code> / <code>unlikely</code> hints in C source, not actually hinting the hardware branch prediction in most CPU, except maybe via static prediction.)</li>\n</ul>\n","owner":"Harsh Sharma","score":1049,"created_at":"2015-07-03T15:35:52.000Z","is_accepted":false,"question_id":11227809,"last_activity_at":"2022-04-22T01:31:28.000Z"}],"question_id":11227809,"quota_remaining":299},"meta":{"timestamp":"2026-06-13T14:46:53.991Z","request_id":"191f2740-c20f-455f-bd6e-d1ea87237569"},"status":"ok","message":"Answers retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/questions":{"get":{"operationId":"get_v1_questions","tags":["Questions"],"summary":"Typed question lists without a search term","description":"","parameters":[{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"},{"name":"sort","in":"query","required":false,"description":"hot (default), votes, activity, week, month or creation","schema":{"type":"string"},"example":"hot"},{"name":"tag","in":"query","required":false,"description":"Filter by a single tag","schema":{"type":"string"},"example":"python"},{"name":"limit","in":"query","required":false,"description":"Max results (1-30)","schema":{"type":"string"},"example":"20"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"tag":"python","site":"stackoverflow","sort":"hot","count":20,"results":[{"id":79958531,"link":"https://stackoverflow.com/questions/79958531/how-to-read-headers-set-by-wsgi-start-response","tags":["python","wsgi","wsgiref","wsgiserver"],"owner":"NickC","score":-1,"title":"How to read headers set by WSGI start_response","created_at":"2026-06-13T14:04:06.000Z","view_count":17,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-13T14:20:47.000Z","accepted_answer_id":79958535},{"id":79958517,"link":"https://stackoverflow.com/questions/79958517/fastapi-returns-422-unprocessable-entity-on-post-from-next-js-fetch-despite-matc","tags":["python","next.js","http-post","fastapi","pydantic"],"owner":"Debanshu Paul","score":-1,"title":"FastAPI returns 422 Unprocessable Entity on POST from Next.js fetch despite matching Pydantic model","created_at":"2026-06-13T13:23:27.000Z","view_count":19,"is_answered":false,"answer_count":1,"last_activity_at":"2026-06-13T13:26:32.000Z"},{"id":79958459,"link":"https://stackoverflow.com/questions/79958459/how-does-python-handle-floating-point-numbers-when-the-round-function-is-also-in","tags":["python","python-idle"],"owner":"Nimish","score":0,"title":"How does Python handle floating point numbers when the round function is also involved?","created_at":"2026-06-13T09:58:35.000Z","view_count":68,"is_answered":true,"answer_count":3,"last_activity_at":"2026-06-13T11:21:08.000Z"},{"id":79958384,"link":"https://stackoverflow.com/questions/79958384/is-it-better-for-users-to-get-raw-information-or-the-tidied-up-information-from","tags":["python"],"owner":"Ellan Aqira","score":0,"title":"Is it better for users to get raw information or the tidied up information from the functions in my python library?","created_at":"2026-06-13T05:17:16.000Z","view_count":64,"is_answered":true,"answer_count":3,"last_activity_at":"2026-06-13T12:31:16.000Z"},{"id":79957247,"link":"https://stackoverflow.com/questions/79957247/selenium-python-readtimeouterror-httpconnectionpoolhost-localhost-port-5348","tags":["python","php","selenium-webdriver"],"owner":"rmor23","score":-1,"title":"Selenium Python ReadTimeoutError: HTTPConnectionPool(host='localhost', port=53487): Read timed out. (read timeout=120)","created_at":"2026-06-12T17:12:38.000Z","view_count":78,"is_answered":false,"answer_count":1,"last_activity_at":"2026-06-13T11:26:12.000Z"},{"id":79957305,"link":"https://stackoverflow.com/questions/79957305/could-this-logging-setup-code-be-rationalised","tags":["python","python-3.x"],"owner":"NickC","score":1,"title":"Could this logging setup code be rationalised","created_at":"2026-06-12T20:02:04.000Z","view_count":77,"is_answered":true,"answer_count":2,"last_activity_at":"2026-06-12T22:09:48.000Z"},{"id":79957336,"link":"https://stackoverflow.com/questions/79957336/how-to-display-names-instead-of-ids-using-django-with-react","tags":["javascript","python","reactjs","django"],"owner":"Andres Vilca","score":0,"title":"How to display names instead of IDs, using Django with React?","created_at":"2026-06-12T22:15:00.000Z","view_count":76,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-12T22:39:54.000Z"},{"id":79957363,"link":"https://stackoverflow.com/questions/79957363/best-way-to-create-absolute-path-to-external-directory-after-bundling-applicatio","tags":["python","pyinstaller","pathlib"],"owner":"Obsidian Asphodel","score":-4,"title":"Best Way to create Absolute Path to External Directory after bundling Application","created_at":"2026-06-13T01:57:09.000Z","view_count":42,"is_answered":false,"answer_count":0,"last_activity_at":"2026-06-13T01:57:09.000Z"},{"id":79957057,"link":"https://stackoverflow.com/questions/79957057/how-do-you-efficiently-export-and-process-large-backlink-datasets-in-python","tags":["python"],"owner":"victoria","score":1,"title":"How do you efficiently export and process large backlink datasets in Python?","created_at":"2026-06-12T10:57:18.000Z","view_count":85,"is_answered":true,"answer_count":4,"last_activity_at":"2026-06-13T06:07:41.000Z"},{"id":79956975,"link":"https://stackoverflow.com/questions/79956975/is-python-an-efficient-way-to-automate-view-table-construction-for-database","tags":["python","postgresql","view","automation"],"owner":"Archipel","score":0,"title":"Is Python an efficient way to automate View/Table construction for database?","created_at":"2026-06-12T08:20:17.000Z","view_count":108,"is_answered":true,"answer_count":13,"last_activity_at":"2026-06-13T05:38:09.000Z"},{"id":79957312,"link":"https://stackoverflow.com/questions/79957312/python-selenium-how-to-download-via-execute-script","tags":["python","selenium-webdriver"],"owner":"JDias","score":0,"title":"Python Selenium - how to download via execute_script","created_at":"2026-06-12T20:17:08.000Z","view_count":64,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-12T23:18:10.000Z","accepted_answer_id":79957349},{"id":79957200,"link":"https://stackoverflow.com/questions/79957200/why-does-divmod-run-slower-than-successive-division-taking-the-remainder","tags":["python","prime-factoring","factorization","divmod"],"owner":"Constantine","score":1,"title":"Why does divmod() run slower than successive division + taking the remainder?","created_at":"2026-06-12T15:18:30.000Z","view_count":90,"is_answered":true,"answer_count":3,"last_activity_at":"2026-06-12T18:35:06.000Z"},{"id":79956737,"link":"https://stackoverflow.com/questions/79956737/how-can-i-get-a-source-code-of-python-function-which-was-declared-by-using-exec","tags":["python","function","inspect"],"owner":"Yaroslav_A","score":2,"title":"How can I get a source code of Python function which was declared by using 'exec' inside other function?","created_at":"2026-06-11T18:49:58.000Z","view_count":140,"is_answered":true,"answer_count":14,"last_activity_at":"2026-06-13T13:21:18.000Z"},{"id":79957020,"link":"https://stackoverflow.com/questions/79957020/how-to-fix-json-decoder-jsondecodeerror-extra-data-line-2-column-1-char-9035","tags":["python","json"],"owner":"Lugger Lug","score":-4,"title":"How to fix json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 9035) without modifying a file?","created_at":"2026-06-12T09:43:18.000Z","view_count":85,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-12T23:17:33.000Z","accepted_answer_id":79957022},{"id":79957069,"link":"https://stackoverflow.com/questions/79957069/counting-items-in-column-or-why-is-my-code-only-counting-one-item-in-the-string","tags":["python","pandas"],"owner":"Dragoran21","score":-2,"title":"Counting items in column or why is my code only counting one item in the string?","created_at":"2026-06-12T11:22:11.000Z","view_count":117,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-12T15:39:22.000Z"},{"id":79956908,"link":"https://stackoverflow.com/questions/79956908/await-may-it-be-called-several-times-and-then-wait-again","tags":["python","python-3.x","async-await","python-asyncio"],"owner":"glglgl","score":0,"title":"__await__: may it be called several times and then wait again?","created_at":"2026-06-12T06:04:48.000Z","view_count":103,"is_answered":true,"answer_count":3,"last_activity_at":"2026-06-12T19:01:23.000Z"},{"id":79956503,"link":"https://stackoverflow.com/questions/79956503/how-to-count-how-many-times-string-x-appears-in-a-row-and-how-to-turn-answer-in","tags":["python","pandas"],"owner":"Dragoran21","score":0,"title":"How to count how many times string X appears in a row (and how to turn answer into a table)?","created_at":"2026-06-11T12:18:12.000Z","view_count":138,"is_answered":true,"answer_count":9,"last_activity_at":"2026-06-13T08:47:17.000Z"},{"id":79956996,"link":"https://stackoverflow.com/questions/79956996/define-a-type-as-a-union-of-constants","tags":["python","python-typing"],"owner":"Remco Haszing","score":1,"title":"Define a type as a union of constants","created_at":"2026-06-12T08:56:23.000Z","view_count":90,"is_answered":true,"answer_count":1,"last_activity_at":"2026-06-12T09:39:55.000Z","accepted_answer_id":79957015},{"id":79956885,"link":"https://stackoverflow.com/questions/79956885/vectorising-weight-average-over-time","tags":["python","numpy","vectorization"],"owner":"orange","score":1,"title":"Vectorising weight average over time","created_at":"2026-06-12T04:42:25.000Z","view_count":91,"is_answered":false,"answer_count":1,"last_activity_at":"2026-06-12T19:57:34.000Z"},{"id":79957194,"link":"https://stackoverflow.com/questions/79957194/azure-durable-functions-fan-out-fan-in-with-durable-timers","tags":["python","azure-functions"],"owner":"euh","score":0,"title":"Azure Durable Functions Fan-out/Fan-in with Durable Timers","created_at":"2026-06-12T14:59:41.000Z","view_count":31,"is_answered":false,"answer_count":0,"last_activity_at":"2026-06-12T14:59:41.000Z"}],"quota_remaining":298},"meta":{"timestamp":"2026-06-13T14:46:55.013Z","request_id":"38b2b20f-e42f-4e31-bc62-f60916518f32"},"status":"ok","message":"Questions retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/tags":{"get":{"operationId":"get_v1_tags","tags":["Tags"],"summary":"A site's tags by popularity or name","description":"","parameters":[{"name":"site","in":"query","required":false,"description":"Stack Exchange site slug (default stackoverflow; see /v1/sites)","schema":{"type":"string"},"example":"stackoverflow"},{"name":"sort","in":"query","required":false,"description":"popular (default) or name","schema":{"type":"string"},"example":"popular"},{"name":"limit","in":"query","required":false,"description":"Max results (1-50)","schema":{"type":"string"},"example":"25"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"site":"stackoverflow","sort":"popular","count":25,"results":[{"name":".net","count":341642,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"android","count":1418133,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"arrays","count":418296,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"asp.net","count":373555,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"c","count":409820,"is_required":false,"has_synonyms":false,"is_moderator_only":false},{"name":"c#","count":1626252,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"c++","count":818063,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"css","count":808907,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"django","count":312259,"is_required":false,"has_synonyms":false,"is_moderator_only":false},{"name":"html","count":1189533,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"ios","count":689557,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"java","count":1921132,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"javascript","count":2530944,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"jquery","count":1030770,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"json","count":361258,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"mysql","count":658850,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"node.js","count":472677,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"php","count":1464718,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"python","count":2219855,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"python-3.x","count":342277,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"r","count":512186,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"reactjs","count":478540,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"ruby-on-rails","count":338107,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"sql","count":675336,"is_required":false,"has_synonyms":true,"is_moderator_only":false},{"name":"sql-server","count":337195,"is_required":false,"has_synonyms":true,"is_moderator_only":false}],"quota_remaining":299},"meta":{"timestamp":"2026-06-13T14:46:55.679Z","request_id":"2e117dd5-2668-4ea6-9413-fa4164bd56b9"},"status":"ok","message":"Tags retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}},"/v1/sites":{"get":{"operationId":"get_v1_sites","tags":["Meta"],"summary":"Directory of Stack Exchange sites","description":"","parameters":[{"name":"limit","in":"query","required":false,"description":"Page size (1-100)","schema":{"type":"string"},"example":"50"},{"name":"page","in":"query","required":false,"description":"Page (1-20)","schema":{"type":"string"},"example":"1"}],"security":[{"oanorKey":[]}],"responses":{"200":{"description":"OK","content":{"application/json":{"example":{"data":{"page":1,"count":50,"results":[{"name":"Stack Overflow","slug":"stackoverflow","audience":"professional and enthusiast programmers","icon_url":"https://stackoverflow.com/Content/Sites/stackoverflow/Img/apple-touch-icon.png","site_url":"https://stackoverflow.com","site_type":"main_site"},{"name":"Server Fault","slug":"serverfault","audience":"system and network administrators","icon_url":"https://serverfault.com/Content/Sites/serverfault/Img/apple-touch-icon.png","site_url":"https://serverfault.com","site_type":"main_site"},{"name":"Super User","slug":"superuser","audience":"computer enthusiasts and power users","icon_url":"https://superuser.com/Content/Sites/superuser/Img/apple-touch-icon.png","site_url":"https://superuser.com","site_type":"main_site"},{"name":"Meta Stack Exchange","slug":"meta","audience":"meta-discussion of the Stack Exchange family of Q&amp;A websites","icon_url":"https://meta.stackexchange.com/Content/Sites/stackexchangemeta/Img/apple-touch-icon.png","site_url":"https://meta.stackexchange.com","site_type":"main_site"},{"name":"Web Applications","slug":"webapps","audience":"power users of web applications","icon_url":"https://webapps.stackexchange.com/Content/Sites/webapps/Img/apple-touch-icon.png","site_url":"https://webapps.stackexchange.com","site_type":"main_site"},{"name":"Web Applications Meta","slug":"webapps.meta","audience":"power users of web applications","icon_url":"https://webapps.meta.stackexchange.com/Content/Sites/webappsmeta/Img/apple-touch-icon.png","site_url":"https://webapps.meta.stackexchange.com","site_type":"meta_site"},{"name":"Arqade","slug":"gaming","audience":"passionate videogamers on all platforms","icon_url":"https://gaming.stackexchange.com/Content/Sites/gaming/Img/apple-touch-icon.png","site_url":"https://gaming.stackexchange.com","site_type":"main_site"},{"name":"Arqade Meta","slug":"gaming.meta","audience":"passionate videogamers on all platforms","icon_url":"https://gaming.meta.stackexchange.com/Content/Sites/gamingmeta/Img/apple-touch-icon.png","site_url":"https://gaming.meta.stackexchange.com","site_type":"meta_site"},{"name":"Webmasters","slug":"webmasters","audience":"webmasters","icon_url":"https://webmasters.stackexchange.com/Content/Sites/webmasters/Img/apple-touch-icon.png","site_url":"https://webmasters.stackexchange.com","site_type":"main_site"},{"name":"Webmasters Meta","slug":"webmasters.meta","audience":"webmasters","icon_url":"https://webmasters.meta.stackexchange.com/Content/Sites/webmastersmeta/Img/apple-touch-icon.png","site_url":"https://webmasters.meta.stackexchange.com","site_type":"meta_site"},{"name":"Seasoned Advice","slug":"cooking","audience":"professional and amateur chefs","icon_url":"https://cooking.stackexchange.com/Content/Sites/cooking/Img/apple-touch-icon.png","site_url":"https://cooking.stackexchange.com","site_type":"main_site"},{"name":"Seasoned Advice Meta","slug":"cooking.meta","audience":"professional and amateur chefs","icon_url":"https://cooking.meta.stackexchange.com/Content/Sites/cookingmeta/Img/apple-touch-icon.png","site_url":"https://cooking.meta.stackexchange.com","site_type":"meta_site"},{"name":"Game Development","slug":"gamedev","audience":"professional and independent game developers","icon_url":"https://gamedev.stackexchange.com/Content/Sites/gamedev/Img/apple-touch-icon.png","site_url":"https://gamedev.stackexchange.com","site_type":"main_site"},{"name":"Game Development Meta","slug":"gamedev.meta","audience":"professional and independent game developers","icon_url":"https://gamedev.meta.stackexchange.com/Content/Sites/gamedevmeta/Img/apple-touch-icon.png","site_url":"https://gamedev.meta.stackexchange.com","site_type":"meta_site"},{"name":"Photography","slug":"photo","audience":"professional, enthusiast and amateur photographers","icon_url":"https://photo.stackexchange.com/Content/Sites/photo/Img/apple-touch-icon.png","site_url":"https://photo.stackexchange.com","site_type":"main_site"},{"name":"Photography Meta","slug":"photo.meta","audience":"professional, enthusiast and amateur photographers","icon_url":"https://photo.meta.stackexchange.com/Content/Sites/photometa/Img/apple-touch-icon.png","site_url":"https://photo.meta.stackexchange.com","site_type":"meta_site"},{"name":"Cross Validated","slug":"stats","audience":"people interested in statistics, machine learning, data analysis, data mining, and data visualization","icon_url":"https://stats.stackexchange.com/Content/Sites/stats/Img/apple-touch-icon.png","site_url":"https://stats.stackexchange.com","site_type":"main_site"},{"name":"Cross Validated Meta","slug":"stats.meta","audience":"people interested in statistics, machine learning, data analysis, data mining, and data visualization","icon_url":"https://stats.meta.stackexchange.com/Content/Sites/statsmeta/Img/apple-touch-icon.png","site_url":"https://stats.meta.stackexchange.com","site_type":"meta_site"},{"name":"Mathematics","slug":"math","audience":"people studying math at any level and professionals in related fields","icon_url":"https://math.stackexchange.com/Content/Sites/math/Img/apple-touch-icon.png","site_url":"https://math.stackexchange.com","site_type":"main_site"},{"name":"Mathematics Meta","slug":"math.meta","audience":"people studying math at any level and professionals in related fields","icon_url":"https://math.meta.stackexchange.com/Content/Sites/mathmeta/Img/apple-touch-icon.png","site_url":"https://math.meta.stackexchange.com","site_type":"meta_site"},{"name":"Home Improvement","slug":"diy","audience":"contractors and serious DIYers","icon_url":"https://diy.stackexchange.com/Content/Sites/diy/Img/apple-touch-icon.png","site_url":"https://diy.stackexchange.com","site_type":"main_site"},{"name":"Home Improvement Meta","slug":"diy.meta","audience":"contractors and serious DIYers","icon_url":"https://diy.meta.stackexchange.com/Content/Sites/diymeta/Img/apple-touch-icon.png","site_url":"https://diy.meta.stackexchange.com","site_type":"meta_site"},{"name":"Meta Super User","slug":"meta.superuser","audience":"computer enthusiasts and power users","icon_url":"https://meta.superuser.com/Content/Sites/superusermeta/Img/apple-touch-icon.png","site_url":"https://meta.superuser.com","site_type":"meta_site"},{"name":"Meta Server Fault","slug":"meta.serverfault","audience":"system and network administrators","icon_url":"https://meta.serverfault.com/Content/Sites/serverfaultmeta/Img/apple-touch-icon.png","site_url":"https://meta.serverfault.com","site_type":"meta_site"},{"name":"Geographic Information Systems","slug":"gis","audience":"cartographers, geographers and GIS professionals","icon_url":"https://gis.stackexchange.com/Content/Sites/gis/Img/apple-touch-icon.png","site_url":"https://gis.stackexchange.com","site_type":"main_site"},{"name":"Geographic Information Systems Meta","slug":"gis.meta","audience":"cartographers, geographers and GIS professionals","icon_url":"https://gis.meta.stackexchange.com/Content/Sites/gismeta/Img/apple-touch-icon.png","site_url":"https://gis.meta.stackexchange.com","site_type":"meta_site"},{"name":"TeX - LaTeX","slug":"tex","audience":"users of TeX, LaTeX, ConTeXt, and related typesetting systems","icon_url":"https://tex.stackexchange.com/Content/Sites/tex/Img/apple-touch-icon.png","site_url":"https://tex.stackexchange.com","site_type":"main_site"},{"name":"TeX - LaTeX Meta","slug":"tex.meta","audience":"users of TeX, LaTeX, ConTeXt, and related typesetting systems","icon_url":"https://tex.meta.stackexchange.com/Content/Sites/texmeta/Img/apple-touch-icon.png","site_url":"https://tex.meta.stackexchange.com","site_type":"meta_site"},{"name":"Ask Ubuntu","slug":"askubuntu","audience":"Ubuntu users and developers","icon_url":"https://askubuntu.com/Content/Sites/askubuntu/Img/apple-touch-icon.png","site_url":"https://askubuntu.com","site_type":"main_site"},{"name":"Ask Ubuntu Meta","slug":"meta.askubuntu","audience":"Ubuntu users and developers","icon_url":"https://meta.askubuntu.com/Content/Sites/askubuntumeta/Img/apple-touch-icon.png","site_url":"https://meta.askubuntu.com","site_type":"meta_site"},{"name":"Personal Finance & Money","slug":"money","audience":"people who want to be financially literate","icon_url":"https://money.stackexchange.com/Content/Sites/money/Img/apple-touch-icon.png","site_url":"https://money.stackexchange.com","site_type":"main_site"},{"name":"Personal Finance & Money Meta","slug":"money.meta","audience":"people who want to be financially literate","icon_url":"https://money.meta.stackexchange.com/Content/Sites/moneymeta/Img/apple-touch-icon.png","site_url":"https://money.meta.stackexchange.com","site_type":"meta_site"},{"name":"English Language & Usage","slug":"english","audience":"linguists, etymologists, and serious English language enthusiasts","icon_url":"https://english.stackexchange.com/Content/Sites/english/Img/apple-touch-icon.png","site_url":"https://english.stackexchange.com","site_type":"main_site"},{"name":"English Language & Usage Meta","slug":"english.meta","audience":"linguists, etymologists, and serious English language enthusiasts","icon_url":"https://english.meta.stackexchange.com/Content/Sites/englishmeta/Img/apple-touch-icon.png","site_url":"https://english.meta.stackexchange.com","site_type":"meta_site"},{"name":"Stack Apps","slug":"stackapps","audience":"apps, scripts, and development with the Stack Exchange API","icon_url":"https://stackapps.com/Content/Sites/stackapps/Img/apple-touch-icon.png","site_url":"https://stackapps.com","site_type":"main_site"},{"name":"User Experience","slug":"ux","audience":"user experience researchers and experts","icon_url":"https://ux.stackexchange.com/Content/Sites/ux/Img/apple-touch-icon.png","site_url":"https://ux.stackexchange.com","site_type":"main_site"},{"name":"User Experience Meta","slug":"ux.meta","audience":"user experience researchers and experts","icon_url":"https://ux.meta.stackexchange.com/Content/Sites/uxmeta/Img/apple-touch-icon.png","site_url":"https://ux.meta.stackexchange.com","site_type":"meta_site"},{"name":"Unix & Linux","slug":"unix","audience":"users of Linux, FreeBSD and other Un*x-like operating systems","icon_url":"https://unix.stackexchange.com/Content/Sites/unix/Img/apple-touch-icon.png","site_url":"https://unix.stackexchange.com","site_type":"main_site"},{"name":"Unix & Linux Meta","slug":"unix.meta","audience":"users of Linux, FreeBSD and other Un*x-like operating systems","icon_url":"https://unix.meta.stackexchange.com/Content/Sites/unixmeta/Img/apple-touch-icon.png","site_url":"https://unix.meta.stackexchange.com","site_type":"meta_site"},{"name":"WordPress Development","slug":"wordpress","audience":"WordPress developers and administrators","icon_url":"https://wordpress.stackexchange.com/Content/Sites/wordpress/Img/apple-touch-icon.png","site_url":"https://wordpress.stackexchange.com","site_type":"main_site"},{"name":"WordPress Development Meta","slug":"wordpress.meta","audience":"WordPress developers and administrators","icon_url":"https://wordpress.meta.stackexchange.com/Content/Sites/wordpressmeta/Img/apple-touch-icon.png","site_url":"https://wordpress.meta.stackexchange.com","site_type":"meta_site"},{"name":"Theoretical Computer Science","slug":"cstheory","audience":"theoretical computer scientists and researchers in related fields","icon_url":"https://cstheory.stackexchange.com/Content/Sites/cstheory/Img/apple-touch-icon.png","site_url":"https://cstheory.stackexchange.com","site_type":"main_site"},{"name":"Theoretical Computer Science Meta","slug":"cstheory.meta","audience":"theoretical computer scientists and researchers in related fields","icon_url":"https://cstheory.meta.stackexchange.com/Content/Sites/cstheorymeta/Img/apple-touch-icon.png","site_url":"https://cstheory.meta.stackexchange.com","site_type":"meta_site"},{"name":"Ask Different","slug":"apple","audience":"power users of Apple hardware and software","icon_url":"https://apple.stackexchange.com/Content/Sites/apple/Img/apple-touch-icon.png","site_url":"https://apple.stackexchange.com","site_type":"main_site"},{"name":"Ask Different Meta","slug":"apple.meta","audience":"power users of Apple hardware and software","icon_url":"https://apple.meta.stackexchange.com/Content/Sites/applemeta/Img/apple-touch-icon.png","site_url":"https://apple.meta.stackexchange.com","site_type":"meta_site"},{"name":"Role-playing Games","slug":"rpg","audience":"gamemasters and players of tabletop, paper-and-pencil role-playing games","icon_url":"https://rpg.stackexchange.com/Content/Sites/rpg/Img/apple-touch-icon.png","site_url":"https://rpg.stackexchange.com","site_type":"main_site"},{"name":"Role-playing Games Meta","slug":"rpg.meta","audience":"gamemasters and players of tabletop, paper-and-pencil role-playing games","icon_url":"https://rpg.meta.stackexchange.com/Content/Sites/rpgmeta/Img/apple-touch-icon.png","site_url":"https://rpg.meta.stackexchange.com","site_type":"meta_site"},{"name":"Bicycles","slug":"bicycles","audience":"people who build and repair bicycles, people who train cycling, or commute on bicycles","icon_url":"https://bicycles.stackexchange.com/Content/Sites/bicycles/Img/apple-touch-icon.png","site_url":"https://bicycles.stackexchange.com","site_type":"main_site"},{"name":"Bicycles Meta","slug":"bicycles.meta","audience":"people who build and repair bicycles, people who train cycling, or commute on bicycles","icon_url":"https://bicycles.meta.stackexchange.com/Content/Sites/bicyclesmeta/Img/apple-touch-icon.png","site_url":"https://bicycles.meta.stackexchange.com","site_type":"meta_site"},{"name":"Software Engineering","slug":"softwareengineering","audience":"professionals, academics, and students working within the systems development life cycle","icon_url":"https://softwareengineering.stackexchange.com/Content/Sites/softwareengineering/Img/apple-touch-icon.png","site_url":"https://softwareengineering.stackexchange.com","site_type":"main_site"}],"has_more":true},"meta":{"timestamp":"2026-06-13T14:46:56.546Z","request_id":"0ca01eb2-6a2b-43ec-b59b-a890521f60c2"},"status":"ok","message":"Sites retrieved","success":true}}}},"401":{"description":"Missing or invalid x-oanor-key header"},"402":{"description":"Active subscription required"},"429":{"description":"Rate-limit or monthly quota reached"},"502":{"description":"Upstream did not respond"}}}}},"x-oanor-pricing":[{"slug":"free","name":"Free","price_cents_month":0,"monthly_call_quota":4000,"rps_limit":2,"hard_limit":true},{"slug":"basic","name":"Basic","price_cents_month":800,"monthly_call_quota":60000,"rps_limit":8,"hard_limit":true},{"slug":"pro","name":"Pro","price_cents_month":2400,"monthly_call_quota":300000,"rps_limit":20,"hard_limit":true},{"slug":"mega","name":"Mega","price_cents_month":9900,"monthly_call_quota":1500000,"rps_limit":50,"hard_limit":true}],"x-oanor-marketplace-url":"https://www.oanor.com/api/stackexchange-api"}