<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pablo Weremczuk on Medium]]></title>
        <description><![CDATA[Stories by Pablo Weremczuk on Medium]]></description>
        <link>https://medium.com/@pablo.weremczuk?source=rss-2a2608b4f9e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fJsvLwCyy7YDFJJXtlFyvA.jpeg</url>
            <title>Stories by Pablo Weremczuk on Medium</title>
            <link>https://medium.com/@pablo.weremczuk?source=rss-2a2608b4f9e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:04:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pablo.weremczuk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Data Oriented Design in the Frontend — Part 3: Fast Code Saves Battery]]></title>
            <link>https://medium.com/@pablo.weremczuk/data-oriented-design-in-the-frontend-part-3-fast-code-saves-battery-be2fe90bd65d?source=rss-2a2608b4f9e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2fe90bd65d</guid>
            <category><![CDATA[c-programming-language]]></category>
            <category><![CDATA[data-oriented-design]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Pablo Weremczuk]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 13:26:45 GMT</pubDate>
            <atom:updated>2021-05-31T11:12:26.873Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Oriented Design in the Frontend — Part 3: Fast Code Saves Battery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xQybjaYIZ_ncIEM" /><figcaption>Spring in Prague</figcaption></figure><h3>HI! THIS ARTICLE IS IMPRECISE AND MISLEADING(SPECIALLY THE CODE PART). Don’t take it as a qualified opinion. When I wrote this article, didn’t had a good understanding on how this concepts works in code. The examples presented are biased and doesn’t prove the conclusions I’m presenting here. Leaving it as reminder that you should double check everything in internet on your own, SPECIALLY ARTICLES ABOUT PERFORMANCE.</h3><p>(The theory part is kinda ok tho).</p><h3>Original article follows.</h3><p>Energy consumption is very important on cell phones, on laptops, even on datacenters!</p><h3>In the big and the small compute/watt dominates</h3><p>Let’s take mobile applications as an example. The amount of money your app makes usually depends on how much time a user spends on your application. Ads, video on demand, microtransactions and casino games are some examples where the most time a user spends on your program, the more money you make.</p><p>Even if your user doesn’t blame your app for draining the battery, there is no way your app can run in a energy dry phone.</p><p><strong>That’s why power consumption is important in the small.</strong></p><p>On the other side, if you have a big data center where you run your backend on the cloud, the more you scale up your servers, the more money you pay.</p><p>Datacenters are funny places, they not only need energy to power the computers, but also need a lot of electricity for the air conditioner system. You need to cool down all that CPU’s!</p><p>In big companies like google or amazon, there is a point where the energy cost goes away and no matter how much money you have, you just can’t have more energy from the grid.</p><p>Chandler Carruth explains this in detail in his talk from 2014 <a href="https://www.youtube.com/watch?v=fHNmRkzxHWs">“Efficiency with Algorithms, Performance with Data Structures”</a>.</p><h3>But is this true in the browser?</h3><p>In my <a href="https://medium.com/@pablo.weremczuk/data-oriented-design-in-the-frontend-part-2-data-locality-dff852f3800d">last article about <strong>Data Locality</strong></a> we saw how we can make our programs up to <strong>50X faster </strong>using Data Oriented Design.</p><blockquote>If you set your video player 50x faster, you can watch the combined length of the Lord of the Rings trilogy (Extended Editions) in 13 minutes.</blockquote><p>Let’s use this knowledge optimizing a particle system and see if this affects the energy consumption.</p><p>So, the experiment goes like this.</p><ol><li>We create a system of <strong>200.000 particles</strong>. Every particle is represented by a <strong>GameObject</strong> structure in C, so we put all of them in an array. This is called <strong>Array Of Structures</strong> or <strong>AOS</strong>.</li><li>We run the test using a 3D game engine that can compile to native code and web assembly. We are using <a href="https://www.raylib.com/">Raylib</a> for this test.</li><li>We optimize the code migrating from <strong>AOS</strong> to a more <strong>cache-friendly</strong> structure. In order to pack more particles in the cache line.</li></ol><p>The original code looks something like this:</p><pre>#define <strong>PARTICLES_COUNT </strong>2000000</pre><pre><strong>typedef struct </strong>GameObject {<br>    Vector3 position;<br>    Vector3 velocity;<br>    Vector3 acceleration;<br>    Rectangle collision_rectangle;<br>    <em>// Drawable Data<br>    </em>Texture texture;<br>    Vector3 vertices[4];<br>    Rectangle textureRect;<br>    <em>// Transform Data<br>    </em>Vector2 origin;<br><br>    <strong>float </strong>rotation;<br>    Vector2 scale;<br>    Matrix transform;<br>    <strong>bool </strong>transformNeedUpdate;<br>    Matrix inverseTransform;<br>    <strong>bool </strong>inverseTransformNeedUpdate;<br>    <strong>void </strong>*parent;<br><br>    <strong>void</strong>* children[50];<br>} GameObject;</pre><pre><strong>int</strong> main(<strong>void</strong>){</pre><pre><strong>    for</strong>(<strong>unsigned long int </strong>i = 0; i &lt; <strong>PARTICLES_COUNT</strong>; i++){<br>        particles_speed[i] = velocity_create();<br>    }<br>    <br>    <strong>while</strong>(!WindowShouldClose()){<br>        Vector3 delta = Vector3Scale(<strong>GRAVITY</strong>, GetFrameTime());</pre><pre><em>        // Update particles position<br>        </em><strong>float </strong>scalar_delta = GetFrameTime() * <strong>GRAVITY</strong>;</pre><pre>        <em>// Update particles position<br>        </em><strong>for </strong>(uint_fast64_t i = 0; i &lt; <strong>PARTICLES_COUNT</strong>; i++) {<br>            particles[i].velocity.y += scalar_delta;<br><br>            particles[i].position.y += particles[i].velocity.y;<br>            particles[i].position.x += particles[i].velocity.x;<br>            particles[i].position.z += particles[i].velocity.z;<br><br>            <strong>if </strong>(particles[i].position.y &lt;= 0) {<br>                particles[i].position = (Vector3){0, 0, 0, 0};<br>                particles[i].velocity = velocity_create();<br>            }<br>        }</pre><pre>    Draw();</pre><pre>}</pre><p>And the optimized version looks like this:</p><pre>#define <strong>PARTICLES_COUNT </strong>2000000</pre><pre><strong>typedef struct </strong>GameObject {<br>        Vector3 position;<br>        Vector3 velocity;<br>    } GameObject;</pre><pre><strong>typedef struct </strong>FatObject {<br>        Vector3 acceleration;<br>        Rectangle collision_rectangle;<br>        <em>// Drawable Data<br>        </em>Texture texture;<br>        Vector3 vertices[4];<br>        Rectangle textureRect;<br>        <em>// Transform Data<br>        </em>Vector2 origin;<br><br>        <strong>float </strong>rotation;<br>        Vector2 scale;<br>        Matrix transform;<br>        <strong>bool </strong>transformNeedUpdate;<br>        Matrix inverseTransform;<br>        <strong>bool </strong>inverseTransformNeedUpdate;<br>        <strong>void </strong>*parent;<br>        <strong>void</strong>* children[50];<br>} FatObject;</pre><pre><strong>int</strong> main(<strong>void</strong>){</pre><pre><strong>       for</strong>(<strong>unsigned long int </strong>i = 0; i &lt; <strong>PARTICLES_COUNT</strong>; i++){<br>            particles_speed[i] = velocity_create();<br>       }<br>    <br>       <strong>while</strong>(!WindowShouldClose()){<br>           Vector3 delta = Vector3Scale(<strong>GRAVITY</strong>, GetFrameTime());</pre><pre><em>           // Update particles position<br>           </em><strong>float </strong>scalar_delta = GetFrameTime() * <strong>GRAVITY</strong>;</pre><pre><em>           // Update particles position<br>           </em><strong>for </strong>(uint_fast64_t i = 0; i &lt; <strong>PARTICLES_COUNT</strong>; i++) {<br>               particles[i].velocity.y += scalar_delta;<br><br>               particles[i].position.y += particles[i].velocity.y;<br>               particles[i].position.x += particles[i].velocity.x;<br>               particles[i].position.z += particles[i].velocity.z;<br><br>               <strong>if </strong>(particles[i].position.y &lt;= 0) {<br>                  particles[i].position = (Vector3){0, 0, 0, 0};<br>                  particles[i].velocity = velocity_create();<br>               }<br>        }</pre><pre>        Draw();</pre><pre>}</pre><p>The key here is to split the structure in independent arrays to fit as many particles as possible in the CPU cache.</p><p>That&#39;s why the second version is faster, because the memory we are working with smaller and invalidates the cache to a smaller rate while iterating the array.</p><blockquote>This is an important lesson from the revision I did from the original code. The data that is processed together, need to be together. If we split every vector in different arrays of float, and then we use the velocity to increase the position. The code will be actually slower. <strong>Remember, is not always about the cache, but is always about the data.</strong></blockquote><p>For the full code, you can check the <a href="https://github.com/WEREMSOFT/WAD-2020-BERLIN">GitHub repository</a> under the folder 0004-speed-vs-battery. Also, you can check online both, the <a href="https://htmlpreview.github.io/?https://github.com/WEREMSOFT/WAD-2020-BERLIN/blob/master/004-speed-vs-batery/html_cache_friendly/main_cache_friendly.html">cache-friendly version</a> and the <a href="https://htmlpreview.github.io/?https://github.com/WEREMSOFT/WAD-2020-BERLIN/blob/master/004-speed-vs-batery/html_cache_unfriendly/main_cache_unfriendly.html">cache-unfriendly version</a>.</p><h3>Native Code</h3><p>Usually, in games, we are limiting the framerate to <strong>60 fps</strong>, so other more important threads like<strong> sound and input have more CPU power</strong>.</p><p>Also <strong>browsers cap the framerate to 60fps</strong>, even if your main loop is empty, you will never get more than 60 fps in a browser.</p><p>We are going to remove this limitation when compiling to native code and see which version is the fastest, just to prove that our optimization works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*rdl4sdaepOyOetknyP7Cww.png" /></figure><p>We can see that our <strong>cache-friendly</strong> version is almost 2.5x faster than the AOS. So, yes, proved. Both of them are using as much processor as they can, so the energy rating should be pretty hight for both of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVXL6lD8EWWvjXKUNMn-og.png" /><figcaption>Energy impact with no framerate cap</figcaption></figure><p>So yes, our <strong>laptop gets hot in no time</strong> and the battery penalty is high.</p><p>Now, let&#39;s limit the framerate to 60fps, and see the energy impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*dyLPo2bnIp7AjcYYeoKx4Q.png" /></figure><p>Since the <strong>cache-friendly</strong> version finishes its job faster, it has all the remaining time of the frame to sleep, so we see that the optimized version consumes half of the energy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A13hZ3ACt3tShlhUHfpWew.png" /></figure><p>So yes, our optimized version is 2.5x more efficient and almost 3x faster.</p><p>That means that if you create a program using Data Oriented Design approach your battery will last 2.5x times more.</p><p>This means that if all your native apps use Data Oriented Optimizations, the battery on your iPhone XS Max will last 20 hours using it continuously.</p><blockquote>With this optimization, you can watch all the Lord of the Rings trilogy (Extended Editions) on your phone, at normal speed, without charging, and you still have some spare watts on your battery you read this article 10 times!</blockquote><h3>But, What About the Browser?</h3><p>Glad you ask. Let&#39;s take the same C code and compile it to WebAssembly using Emscripten.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BA0SRAnjUAxCrv3TmyPWbg.png" /><figcaption>CPU usage using Task Manager for google chrome</figcaption></figure><p>The unoptimized version uses more CPU as expected. Also the framerate is a little lower.</p><p>But when we want to measure energy consumption, <strong>there is a catch</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZZ89wJHwP2fNMzZk9qMAA.png" /><figcaption>Energy consumption on chrome.</figcaption></figure><p>We can not tell easily which the process on chrome is AOS and which is SOA. Let&#39;s measure them separately, killing one and another with google task manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZ0bSsZ8k2o1tDQdK-NU4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aY5fPzpqHnC_k9kfv0AhKw.png" /></figure><p>Now we can measure the energy consumption of each example!</p><h3>Final Numbers</h3><p>Let’s check the numbers. It seems that we have a winner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZUQQMjJjVW5ZgrVsHZEJg.png" /><figcaption>Look at that!</figcaption></figure><h3>Final Words</h3><p>Using Data Oriented Design on the web not only give us an impressive <strong>performance boost</strong>, but also <strong>saves a lot of energy</strong>.</p><p>The battery on our phones and laptops last longer, but since we can run WebAssembly code on nodeJS, we can <strong>use these same principles on our backend</strong>.</p><h3>One More Thing…</h3><p>Oh, I forgot to tell you, there is one more thing. Since you are using less CPU, your mobile device will not heat that much, which will prevent your CPU to throttle!</p><p>Throttling is also known as <strong>Dynamic Frequency Scaling</strong>, is a technique in computer architecture whereby the frequency of a microprocessor can be automatically adjusted “on the fly” depending on the actual needs, to conserve power and reduce the amount of heat generated by the chip.</p><p>This means that your phone or laptop, or even your desktop computer, will slow down if it gets too hot.</p><p>Using DOD will not only make your <strong>software run faster</strong>, but also makes your software run <strong>faster for a longer period of time</strong>.</p><p>As you can see, the advantages of Data Oriented Dessign stack on the top of each other. And all these optimizations make you earn money, or save money.</p><h3>Coming Next</h3><p>Thanks for dropping by, I&#39;ll publish another article on the subject hopefully next week, where we are going to see the alternatives to handle complexity using Data Oriented Design, see you then.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2fe90bd65d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Oriented Design in the Frontend — Part 2: Data Locality]]></title>
            <link>https://medium.com/@pablo.weremczuk/data-oriented-design-in-the-frontend-part-2-data-locality-dff852f3800d?source=rss-2a2608b4f9e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff852f3800d</guid>
            <category><![CDATA[data-oriented-design]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[c-programming-language]]></category>
            <dc:creator><![CDATA[Pablo Weremczuk]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 19:16:55 GMT</pubDate>
            <atom:updated>2020-04-15T19:16:55.852Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@pablo.weremczuk/data-oriented-design-in-the-frontend-part-1-introduction-8087adfb2899?source=your_stories_page---------------------------">Data Oriented Design in the Frontend — Part 2: </a>Data Locality</h3><p>We are going to discuss the most important concept regarding DOD. Data Locality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jhy7Uh-bF6aD2ke1ASvtzA.jpeg" /></figure><h3>A Programming Phenomena</h3><p>First, we are going to see a programming phenomenon, and then we are going to see why it happens.</p><p>So, pretend we have a matrix, and we want to visit every element on the matrix, we are going to do it in two different ways: Iterating row by row, and iterating column by column.</p><p>Those ways to iterate a matrix have a name: Row Mayor Traverse, and Column Mayor Traverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Agx_guH9oei3Kod77TEPDQ.png" /></figure><p>BUT! since I found these names hard to remember, we are going to call these two ways to traverse the matrix &quot;Cache-Friendly&quot; and &quot;Cache-Unfriendly&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AF1YO8rlRE07A1Hy9BX6KQ.png" /></figure><p>There, easier to remember, isn&#39;t it? Now, back to business.</p><p>The code to traverse the matrices looks like this in javascript:</p><pre>// ROW MAYOR TRAVERSE (cache friendly)<br>for(let i = 0; i &lt; MATRIX_SIZE; i++){<br>    for(let j = 0; j &lt; MATRIX_SIZE; j++){<br>       result += arr[j][i] ;<br>    }<br>}</pre><p>For the second way</p><pre>// COL MAYOR TRAVERSE (cache unfriendly)<br>for(let j = 0; j &lt; MATRIX_SIZE; j++){<br>    for(let i = 0; i &lt; MATRIX_SIZE; i++){<br>       result += arr[j][i] ;<br>    }<br>}</pre><p>The code is almost equal, the change is so small that I had to check several times to be sure that I didn&#39;t mix it up.</p><p>Even is the code is so similar, the Row Mayor Traverse version is <strong>19 times FASTER!!.</strong></p><p>&quot;Oh, that&#39;s because javascript is a horrible language&quot;. Well, look what happens when I try the same algorithm in C#, Java, and C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MhZnsI1Fz3sR2bbw" /></figure><p>When we iterate in row-by-row instead of column-by-column, we have an order of magnitude performance gain!</p><p>&quot;Oh, but who iterates an array like that?!?!&quot;</p><p>Well, before answer that, let&#39;s see first WHY this happens.</p><h3>When the Speed of Light is not Fast Enough</h3><p><a href="https://twitter.com/cmuratori">Casey Muratori</a>, explains very well this concept on his video <a href="https://www.youtube.com/watch?v=T4CjOB0y9nI">Intro to C on Windows</a>, but the video is a little old and I’d like to update the concepts that he explains there.</p><p>The biggest problem today is the time you need to get information from the memory to the CPU registers. Take a look at this image: This is a photo of a Gigabyte TRX40 Aorus Pro motherboard, designed to host a Ryzen Threadripper 3970.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9FRx3BDR0g2wVvf" /></figure><p>An AMD Ryzen threadripper is one of the most powerful computers you can buy today in a computer shop. WHAT A ROCKET! But there is a detail in the image I want you to notice. The distance between the CPU and the memory bank is 5.69 cm, which means around 11cm for a round trip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*5tKKn-7xNhtTeQfm" /><figcaption>Distance from the center of the CPU to the center of the memory.</figcaption></figure><p>In a hypothetical scenario, where you can send a ray of light, to fetch data from the CPU to the memory(ignoring the time that memory needs to look for the data), we want to know how much the CPU needs to wait to get the data into its registers to process it.</p><p>We know this by dividing the speed of light by the number of CPU cycles: <strong>300.000 km/s</strong> split by <strong>4.5 GHz</strong>. That gives us that the light covers 6.67 cm in one CPU cycle. This is NOT fast enough to bring the data in one CPU cycle! <strong>Our data is 11 cm away from the CPU!!. </strong>The most powerful CPU you can buy, can not bring data from the memory fast enough.</p><p>Of course, we don’t use light in the vacuum to move data from the memory to the CPU, in a straight line, we use electricity through copper wires that need to trace big hooks to avoid electronic components in the motherboard. Also, we have a LOT of additional delay waiting for the memory circuitry to look for the address we request, collect it and send it back. To minimize this problem, <strong>the CPU uses cache</strong>.</p><p>In this context, the cache is a small piece of memory that happens to be very fast. It is inside the CPU and has several levels and sizes.</p><p>In the following image, we can see how much the processor needs to wait for the data, depending on which cache is located. Think about “cycles” as the amount of time the CPU can not work on your problem because is waiting for data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MPB6feDZjtS4BOoB" /><figcaption>Latency from different levels of cache compared to memory.</figcaption></figure><p>When I was working on video games (back in the days when flash was a thing), the square root was a very expensive operation.</p><p>The square root is a very common operation because you need it to calculate distance, so we come with very weird tricks to avoid using it. Let&#39;s compare how many cycles take the most expensive operations in the CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3FsRi87bKBC1AfMPRKH5A.png" /></figure><p>We can see here, that the floating-point square root takes &quot;only&quot; between 8 and 21 cycles. If we compare it with the 200 cycles we spend bringing some information from the main memory, this operations are not so bad.</p><p>Actually, there are very few operations that are close to 200 cycles in the worst-case scenario!</p><p>The point here is that it makes more sense to optimize the code in the data access than trying to find better ways to perform operations.</p><p>This was nicely explained in detail by <a href="https://twitter.com/mike_acton">Mike Acton</a> on his GDC talk “<a href="https://www.youtube.com/watch?v=92KFSD3ObrY">Data Oriented Design in C++</a>”.</p><h3>Back to The Matrices</h3><p>Let&#39;s see how this cache thing has anything to do with iterating matrices.</p><p>Imagine that we want to bring a single byte from memory. Turns out that the CPU doesn’t work like that. Instead of a single byte, it brings a piece of memory that is the size of your cache. This is called a cache line.</p><p>The logic behind this is that the CPU says &quot;oh, you want this byte, maybe you want the following bytes, so I&#39;ll bring them to the cache.&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0inamAWuDK5ePQKCoCMz-w.png" /></figure><p>The difference here is that while in the row approach you have one cache miss only when you run out of cache space, in the column approach you have a cache miss in every element!</p><p>Scott Meyers explains this in great detail on his talk <a href="https://www.youtube.com/watch?v=WDIkqP4JbkE">Cpu Caches and Why You Care</a>.</p><p>The bottom line here is that the fastest way to process elements is to put them as close as possible in memory and process them in batch.</p><p>Let’s look at some graphics comparing the difference between the two techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*StoDm8fhIO3K3rSx" /><figcaption>Comparison between different languages</figcaption></figure><p>You can check the code for the tests I used to create this article in <a href="https://github.com/WEREMSOFT/WAD-2020-BERLIN">github</a>, in the folder 0001-traversing-a-matrix.</p><h3>But Who Iterates a Matrix That Way?</h3><p>Not many people. But if you read carefully, the reason why we are 10 or 60 times slower is that the data we want to use is not close enough in memory.</p><p>But what happens if you have a lot of physics objects where you have to update the speed on the Y component based on the gravity? We can do something like this.</p><pre>class GameObject {<br>   Vector3f position; // 4 x 3 bytes = 12 bytes<br>   Vector3d speed; // 12 bytes<br>   int state; // 4 bytes<br>   float mass; // 4 bytes<br>   Sprite* // 8 bytes<br>}</pre><pre>...</pre><pre>GameObject gos[10000] = createALotOfGO();<br>...</pre><pre>for(int i = 0; i &lt; 10000; i++){<br>   gos[i].speed.y += gravity * delta_time;<br>}</pre><p>This is not a real-world example, but it looks A LOT LIKE ONE. In this case, we are pulling 40 bytes at a time to update 4. We have 36 bytes discarded from the cache. This means that in the most powerful computer we can buy today, we have a cache miss 90% of the time in a trivial loop.</p><p>Since most of the software nowadays looks like this, we can say that most of the software is tenths of time slower than it can be.</p><h3>How does This Compare With Other Optimizations?</h3><p>Just to have an idea that how this compares with other techniques that we use to achieve performance, I created some tests in C, and I compile both, in binary under macOS and in Webassembly using Emscripten.</p><p>The first uses SIMD to process an addition on several elements. SIMD is a way to load several data units in unusually long registers, and perform an instruction over that register, which operates over all the data units at the same time. This is where it gets its name: <strong>S</strong>ingle <strong>I</strong>nstruction, <strong>M</strong>ultiple <strong>D</strong>ata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gWsEJfkAhv_rUDvJ" /></figure><p>We can see that the code that uses SIMD is 3x faster.</p><p>Now, let’s see the performance gain with our old friend: <strong>multithreading</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zgujjtjzL6c6XBJT" /></figure><p>Multi-Threaded version is around twice as fast as the sequential version.</p><p>If you compare these graphics with the performance we have using the cache in an efficient way, they look like a joke. We are comparing 60x against 3x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ymlKEwI1_YOfL2z" /></figure><p>Coding for cache efficiency gives us way more performance improvements than avoiding square roots, using SIMD or using multi-threaded techniques.</p><p>You can check the code for the tests I used to create this article in <a href="https://github.com/WEREMSOFT/WAD-2020-BERLIN">github</a>, in the folder 0003-SIMD.</p><h3>Conclusions and Takeaways</h3><p>Wow! that was a lot of land to cover! Let’s make a quick recap of what we saw today:</p><ul><li>If you trash your cache, your software will be very slow.</li><li>The way to be FAST is to tightly pack the data together and process it in batch.</li><li>Most of the software nowadays should be tens of times faster.</li><li>Coding for cache efficiency is <strong>the most</strong> meaningful way to achieve performance.</li></ul><p>In the next article, we are going to see what options we have to code for cache efficiency. See you then.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff852f3800d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Oriented Design in the Frontend — Part 1: Introduction.]]></title>
            <link>https://medium.com/@pablo.weremczuk/data-oriented-design-in-the-frontend-part-1-introduction-8087adfb2899?source=rss-2a2608b4f9e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8087adfb2899</guid>
            <category><![CDATA[data-oriented-design]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[google-chrome]]></category>
            <dc:creator><![CDATA[Pablo Weremczuk]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 20:56:54 GMT</pubDate>
            <atom:updated>2020-04-15T19:25:30.042Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Data Oriented Design in the Frontend — Part 1: Introduction.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHa-iZkVwrxC4QvfDOHbxg.jpeg" /></figure><p>In this series I’m going to show why DOD is so important for modern software and why you should care.</p><p>I’m going to focus on frontend technologies that are used in the browser, but you’ll see that these principles applies to every programming language.</p><p>Data oriented design(DOD) is a way to take advantage of how modern computers are made. It’s a way to achieve mind-blowing performance gains.</p><p><strong>Faster, Smaller, Simpler</strong></p><p>You are going to learn to make your programs run <strong>faster</strong>, be <strong>smaller</strong> and <strong>simpler</strong>. All of this while making yourself more <strong>relevant as a programmer</strong>.</p><p><strong>Browsers as Virtual Machines</strong></p><p>Browsers become a lot like virtual machines, in the sense that they have a hardware abstraction layer, and can run programs closer to the hardware.</p><p>Still, web development is not catching up. The development ecosystem is polluted and the programs that come from the field are wasteful and inefficient. Web applications are too big, too slow, and consume too much electricity.</p><p><strong>Energy Consumption is !Important</strong></p><p>Power consumption is VERY important in the BIG (data centers) and in the small(mobile devices).</p><p>From the perspective of the mobile devices, slow software is the reason why we have to charge our phones several times a day.</p><p>Data Centers from companies like google, amazon, or Netflix, consumes as much energy as you can give them. There is a point that, no matter how much money you are willing to pay, you just can not have more energy.</p><p>This fact is wonderfully explained in the talk from Chandler Carruth from 2014: <a href="https://youtu.be/fHNmRkzxHWs?t=241">“Efficiency with Algorithms, Performance with Data Structures”</a></p><p>The idea behind this is that you want to create code that runs FAST, fast meaning that you are more efficient. That translates on saving processing power, which consumes less energy, that all together means that you need <strong>less money</strong> to run your business.</p><p>I’m going to give you two real-world examples of this:</p><p>1. A bank needs to escalate it’s Amazon infrastructure to provide acceptable services to their employees and clients. Don’t think only on production servers, but also in continuous integration servers that need to run a build for every pull request their developers create. Or <em>High-Frequency Trading</em>, a field that a microsecond is a lot of time.</p><p>2. A casino company that provides slot machines on mobile devices. The more time your players spend in the slot machine game, the more money you make. So you want your game to run fast to keep the phone battery charge as long as possible.</p><p>These are real scenarios that I face in my professional career.</p><p>Let me put it like this: slow programs are a waste of money.</p><p><strong>Next Episode: An Important Concept</strong></p><p>That’s all for today. In the next episode of this series, we are going to explore a concept key to understand how to make programs run FAST: <strong>Data Locality</strong>. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8087adfb2899" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>