<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Rahul - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Rahul - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 18 May 2026 22:34:21 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/RAHULISM/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Why Your Code is Slow: Common  Performance Mistakes Beginners Make ]]>
                </title>
                <description>
                    <![CDATA[ Maybe you’ve experienced something like this before: you’ve written code that works, but when you hit “run,” it takes forever. You stare at the spinner, wondering if it’s faster to just solve the problem by hand. But you end up looking something like... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/why-your-code-is-slow-common-performance-mistakes-beginners-make/</link>
                <guid isPermaLink="false">67e6c26a4c687a76c3f3934d</guid>
                
                    <category>
                        <![CDATA[ #codenewbies ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Fri, 28 Mar 2025 15:38:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743176201295/448f0407-8a15-4b59-a91f-8a197bc07578.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Maybe you’ve experienced something like this before: you’ve written code that works, but when you hit “run,” it takes forever. You stare at the spinner, wondering if it’s faster to just solve the problem by hand.</p>
<p>But you end up looking something like this… 😭⬇️⬇️</p>
<p><img src="https://img.ifunny.co/images/9eeae78f1bc92e6dc422c5e6af2b5a768913d2e4fa9df2d0df499c1202dfe539_1.jpg" alt="6 year old me thinking the game would load faster if i act like don't care  ORIGINALWOLFF - iFunny" width="1080" height="1100" loading="lazy"></p>
<p>Here’s the truth: slow code doesn’t have to be the end of the world. And it’s a rite of passage if you’re a developer.</p>
<p>When you’re learning to code, you’re focused on making things <em>work</em>—not making them fast. But eventually, you’ll hit a wall: your app freezes, your data script takes hours, or your game lags like a PowerPoint slideshow.</p>
<p>The difference between working code and blazing-fast code often comes down to avoiding a few common mistakes. Mistakes that are easy to make when you’re starting out, like using the wrong tool for the job, writing unnecessary code, or accidentally torturing your computer with hidden inefficiencies.</p>
<p>I’ve been there. I once wrote a “quick” script to analyze data. It ran for 3 hours. Turns out, changing one line of code cut it to 10 seconds. Yes I was dumb when I was learning – but I don’t want you to be, too.</p>
<p>That’s the power of understanding performance.</p>
<p>In this guide, I’ll break down seven common mistakes that can really tank your code’s speed—and how to fix them.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-mistake-1-logging-everything-in-production-without-realizing-it">Mistake #1: Logging Everything in Production (Without Realizing It)</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-fix-it">How to Fix It</a></li>
</ul>
</li>
</ol>
<ol start="2">
<li><p><a class="post-section-overview" href="#heading-mistake-2-using-the-wrong-loops-when-theres-a-faster-alternative">Mistake #2: Using the Wrong Loops (When There’s a Faster Alternative)</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-why-this-is-a-problem-1">Why This is a Problem</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-mistake-3-writing-database-queries-inside-loops-killer-of-speed">Mistake #3: Writing Database Queries Inside Loops (Killer of Speed)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-this-is-a-problem-2">Why This is a Problem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-fix-it-use-bulk-queries">How to Fix It: Use Bulk Queries</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-more-scalable-approach">A More Scalable Approach</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-mistake-4-not-knowing-your-hardwares-dirty-secrets">Mistake #4: Not Knowing Your Hardware’s Dirty Secrets</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-problem-1-the-cpus-crystal-ball-is-broken-memory-prefetching">Problem 1: The CPU’s Crystal Ball is Broken (Memory Prefetching)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-use-contiguous-data-structures">The Fix: Use Contiguous Data Structures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-2-the-invisible-tax-of-memory-pages-tlb-thrashing">Problem 2: The Invisible Tax of Memory Pages (TLB Thrashing)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-process-data-in-chunks">The Fix: Process Data in Chunks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-3-your-code-is-a-tourist-in-the-wrong-cpu-neighborhood-numa">Problem 3: Your Code is a Tourist in the Wrong CPU Neighborhood (NUMA)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-pin-processes-to-numa-aware-memory">The Fix: Pin Processes to NUMA-Aware Memory</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-4-the-cpu-is-a-drama-queen-speculative-execution">Problem 4: The CPU is a Drama Queen (Speculative Execution)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-make-branches-predictable">The Fix: Make Branches Predictable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-fight-back">How to Fight Back</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-mistake-5-memory-fragmentation">Mistake #5: Memory Fragmentation</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-whats-happening-under-the-hood">What’s Happening Under the Hood</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-2-the-autoboxing-trap-java-c-and-so-on">Problem 2: The Autoboxing Trap (Java, C#, and so on)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-use-primitive-collections">The Fix: Use Primitive Collections</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fix-for-c">The Fix for C#</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-mistake-6-the-cache-catch">Mistake #6: The Cache (catch)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-row-major-vs-column-major-access">Row-Major vs. Column-Major Access</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-plot-twist-your-programming-language-is-gaslighting-you">The Plot Twist: Your Programming Language is Gaslighting You</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-multidimensional-illusion-3d-arrays">The Multidimensional Illusion: 3D+ Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-nuclear-option-cache-aware-algorithms">The Nuclear Option: Cache-Aware Algorithms</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-mistake-7-the-copy-paste-trap">Mistake #7: The Copy-Paste Trap</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-problem-1-the-ghost-copies-in-harmless-operations">Problem 1: The Ghost Copies in “Harmless” Operations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-2-the-hidden-cost-of-functional-code">Problem 2: The Hidden Cost of “Functional” Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-problem-3-the-ill-just-modify-a-copy-mistake">Problem 3: The “I’ll Just Modify a Copy” Mistake</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-escape-the-copy-paste-hell">How to Escape the Copy-Paste hell?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-pro-developers-write-faster-code">How Do Pro Developers Write Faster Code?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-they-profile-their-code-instead-of-guessing">1. They Profile Their Code Instead of Guessing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-they-avoid-premature-optimization">2. They Avoid Premature Optimization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-they-pick-the-right-data-structures-not-just-whats-familiar">3. They Pick the Right Data Structures (Not Just What’s Familiar)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-they-automate-performance-checks">4. They Automate Performance Checks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-they-think-about-performance-from-day-one">5. They Think About Performance From Day One</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts-lessons-learned-the-hard-way">Final Thoughts: Lessons Learned the Hard Way</a></p>
</li>
</ol>
<h2 id="heading-mistake-1-logging-everything-in-production-without-realizing-it"><strong>Mistake #1: Logging Everything in Production (Without Realizing It)</strong></h2>
<p>Logging is supposed to help you understand what’s happening in your code—but if you’re logging everything, you’re actually slowing it down. A common beginner mistake is leaving <code>print()</code> statements everywhere or enabling verbose logging even in production, where performance matters most.</p>
<p>Instead of logging only what’s useful, they log every function call, every input, every output, and sometimes even entire request bodies or database queries. This might seem harmless, but in a live application handling thousands of operations per second, excessive logging can cause major slowdowns.</p>
<h3 id="heading-why-this-is-a-problem">Why This is a Problem</h3>
<p>Logging isn’t free. Every log message, whether printed to the console or written to a file, adds extra processing time. If logging is done synchronously (which it often is by default), your application can pause execution while waiting for the log to be recorded.</p>
<p>It also wastes disk space. If every request gets logged in detail, log files can grow rapidly, eating up storage and making it harder to find useful information when debugging.</p>
<p>Here’s an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_data</span>(<span class="hljs-params">data</span>):</span>
    print(<span class="hljs-string">f"Processing data: <span class="hljs-subst">{data}</span>"</span>)  <span class="hljs-comment"># Logging every input</span>
    result = data * <span class="hljs-number">2</span>  
    print(<span class="hljs-string">f"Result: <span class="hljs-subst">{result}</span>"</span>)  <span class="hljs-comment"># Logging every result</span>
    <span class="hljs-keyword">return</span> result
</code></pre>
<p>If this function is running inside a loop handling 10,000+ operations, those print statements are slowing things down massively.</p>
<h3 id="heading-how-to-fix-it">How to Fix It</h3>
<p>Instead of logging everything, focus on logging only what actually matters. Good logging helps you diagnose real issues without cluttering your logs or slowing down your app.</p>
<p>For example, let’s say you're processing user transactions. You don’t need to log every step of the calculation, but logging when a transaction starts, succeeds, or fails is valuable.</p>
<pre><code class="lang-python">// ✅ Bad logging

logging.info(<span class="hljs-string">f"Received input: <span class="hljs-subst">{data}</span>"</span>)  
logging.info(<span class="hljs-string">f"Processing transaction for user <span class="hljs-subst">{user_id}</span>"</span>)  
logging.info(<span class="hljs-string">f"Transaction intermediate step 1 result: <span class="hljs-subst">{some_var}</span>"</span>)  
logging.info(<span class="hljs-string">f"Transaction intermediate step 2 result: <span class="hljs-subst">{another_var}</span>"</span>)  
logging.info(<span class="hljs-string">f"Transaction completed: <span class="hljs-subst">{final_result}</span>"</span>)  

// ✅ Better logging

logging.info(<span class="hljs-string">f"Processing transaction for user <span class="hljs-subst">{user_id}</span>"</span>)  
logging.info(<span class="hljs-string">f"Transaction successful. Amount: $<span class="hljs-subst">{amount}</span>"</span>)
</code></pre>
<p>Next, make sure debugging logs are turned off in production. Debug logs (<code>logging.debug()</code>) are great while developing because they show detailed information, but they shouldn’t be running on live servers.</p>
<p>You can control this by setting the logging level to <code>INFO</code> or higher:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging

logging.basicConfig(level=logging.INFO)  <span class="hljs-comment"># Only logs INFO, WARNING, ERROR, CRITICAL messages</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_data</span>(<span class="hljs-params">data</span>):</span>
    logging.debug(<span class="hljs-string">f"Processing data: <span class="hljs-subst">{data}</span>"</span>)  <span class="hljs-comment"># Won't show up in production</span>
    <span class="hljs-keyword">return</span> data * <span class="hljs-number">2</span>
</code></pre>
<p>Finally, for high-performance applications, consider using asynchronous logging. By default, logging operations can block execution, meaning your program waits until the log message is written before continuing. This can be a bottleneck, especially if you're logging to a file or a remote logging service.</p>
<p>Asynchronous logging solves this by handling logs in the background. Here’s how you can set it up with Python’s <code>QueueHandler</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> logging.handlers
<span class="hljs-keyword">import</span> queue

log_queue = queue.Queue()
queue_handler = logging.handlers.QueueHandler(log_queue)
logger = logging.getLogger()
logger.addHandler(queue_handler)
logger.setLevel(logging.INFO)

logger.info(<span class="hljs-string">"This log is handled asynchronously!"</span>)
</code></pre>
<h2 id="heading-mistake-2-using-the-wrong-loops-when-theres-a-faster-alternative"><strong>Mistake #2: Using the Wrong Loops (When There’s a Faster Alternative)</strong></h2>
<h3 id="heading-why-this-is-a-problem-1">Why This is a Problem</h3>
<p>Loops are one of the first things you learn in programming, and for loops feel natural—they give you control, they’re easy to understand, and they work everywhere. That’s why beginners tend to reach for them automatically.</p>
<p>But just because something works doesn’t mean it’s the best way. In Python, for loops can be slow—especially when there’s a built-in alternative that does the same job faster and more efficiently.</p>
<p>This isn’t just a Python thing. Most programming languages have optimized ways to handle loops under the hood—whether it's vectorized operations in NumPy, functional programming in JavaScript, or stream processing in Java. Knowing when to use them is key to writing fast, clean code.</p>
<h4 id="heading-example">Example</h4>
<p>Let’s say you want to square a list of numbers. A beginner might write this:</p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
squared = []

<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers:
    squared.append(num ** <span class="hljs-number">2</span>)
</code></pre>
<p>Looks fine, right? But there are two inefficiencies here:</p>
<ol>
<li><p>You're manually looping when Python has a better, built-in way to handle this.</p>
</li>
<li><p>You're making repeated <code>.append()</code> calls, which add unnecessary overhead.</p>
</li>
</ol>
<p>In small cases, you won’t notice a difference. But when processing large datasets, these inefficiencies add up fast.</p>
<h3 id="heading-the-better-faster-way">The Better, Faster Way</h3>
<p>Python has built-in optimizations that make loops run faster. One of them is list comprehensions, which are optimized in C and run significantly faster than manual loops. Here’s how you can rewrite the example:</p>
<pre><code class="lang-python">pythonCopyEdit<span class="hljs-comment"># Much faster and cleaner</span>
squared = [num ** <span class="hljs-number">2</span> <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers]
</code></pre>
<h4 id="heading-why-this-is-better">Why this is better:</h4>
<ol>
<li><p><strong>It’s faster.</strong> List comprehensions run in C under the hood, meaning they don’t have the overhead of Python function calls like <code>.append()</code>.</p>
</li>
<li><p><strong>It eliminates extra work.</strong> Instead of growing a list dynamically (which requires resizing in memory), Python pre-allocates space for the entire list. This makes the operation much more efficient.</p>
</li>
<li><p><strong>It’s more readable.</strong> The intent is clear: "I’m creating a list by squaring each number"—no need to scan through multiple lines of code.</p>
</li>
<li><p><strong>It’s less error-prone.</strong> Since everything happens in a single expression, there’s less chance of accidentally modifying the list incorrectly (for example, forgetting to <code>.append()</code>).</p>
</li>
</ol>
<h3 id="heading-when-to-use-for-loops-vs-list-comprehensions">When to Use For Loops vs. List Comprehensions</h3>
<p>For loops still have their place. Use them when:</p>
<ul>
<li><p>You need complex logic inside the loop (for example, multiple operations per iteration).</p>
</li>
<li><p>You need to modify existing data in place rather than create a new list.</p>
</li>
<li><p>The operation involves side effects, like logging, file writing, or network requests.</p>
</li>
</ul>
<p>Otherwise, list comprehensions should be your default choice for simple transformations. They’re faster, cleaner, and make your Python code more efficient.</p>
<h2 id="heading-mistake-3-writing-database-queries-inside-loops-killer-of-speed"><strong>Mistake #3: Writing Database Queries Inside Loops (Killer of Speed)</strong></h2>
<h3 id="heading-why-this-is-a-problem-2"><strong>Why This is a Problem</strong></h3>
<p>This is one of the biggest slow-code mistakes beginners (and even intermediates) make. It happens because loops feel natural, and database queries feel straightforward. But mix the two together, and you’ve got a performance disaster.</p>
<p>Every time you call a database inside a loop, you're making repeated trips to the database. Each query adds network latency, processing overhead, and unnecessary load on your system.</p>
<h4 id="heading-example-1">Example:</h4>
<p>Imagine you’re fetching user details for a list of <code>user_ids</code> like this:</p>
<pre><code class="lang-python">pythonCopyEdituser_ids = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

<span class="hljs-keyword">for</span> user_id <span class="hljs-keyword">in</span> user_ids:
    user = db.query(<span class="hljs-string">f"SELECT * FROM users WHERE id = <span class="hljs-subst">{user_id}</span>"</span>)
    print(user)  <span class="hljs-comment"># Do something with the user</span>
</code></pre>
<p><strong>What's wrong here?</strong></p>
<ul>
<li><p>You're hitting the database multiple times instead of once.</p>
</li>
<li><p>Each call has network overhead (database queries aren’t instant).</p>
</li>
<li><p>Performance tanks when user_ids gets large.</p>
</li>
</ul>
<h3 id="heading-how-to-fix-it-use-bulk-queries"><strong>How to Fix It: Use Bulk Queries</strong></h3>
<p>Instead of making 5 separate queries, make one:</p>
<pre><code class="lang-python">pythonCopyEdituser_ids = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

users = db.query(<span class="hljs-string">f"SELECT * FROM users WHERE id IN (<span class="hljs-subst">{<span class="hljs-string">','</span>.join(map(str, user_ids))}</span>)"</span>)

<span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users:
    print(user)  <span class="hljs-comment"># Process users efficiently</span>
</code></pre>
<p><strong>Why this is better:</strong></p>
<ul>
<li><p>In the above code, we just have one database call instead of many. This results in faster performance.</p>
</li>
<li><p>There’s also less network overhead which makes your app feel snappier.</p>
</li>
<li><p>And this works even if <code>user_ids</code> has 10,000+ entries.</p>
</li>
</ul>
<h3 id="heading-a-more-scalable-approach"><strong>A More Scalable Approach</strong></h3>
<p>If you're using an ORM (like SQLAlchemy in Python or Sequelize in JavaScript), use batch fetching instead of looping:</p>
<pre><code class="lang-python">pythonCopyEditusers = db.query(User).filter(User.id.in_(user_ids)).all()
</code></pre>
<h2 id="heading-mistake-4-not-knowing-your-hardwares-dirty-secrets"><strong>Mistake #4: Not Knowing Your Hardware’s Dirty Secrets</strong></h2>
<p>Your code doesn’t run in a magical fairyland—it runs on real hardware. CPUs, memory, and caches have quirks that can turn “logically fast” code into a sluggish mess. Here’s what most tutorials won’t tell you:</p>
<h3 id="heading-problem-1-the-cpus-crystal-ball-is-broken-memory-prefetching"><strong>Problem 1: The CPU’s Crystal Ball is Broken (Memory Prefetching)</strong></h3>
<h4 id="heading-what-you-think-happens">What you think happens:</h4>
<p><em>“I’m looping through data sequentially. The CPU should predict what I need next!”</em></p>
<h4 id="heading-what-actually-happens">What actually happens:</h4>
<p>Modern CPUs have a memory prefetcher—a smart assistant that tries to guess which memory locations you’ll need next and loads them in advance.</p>
<p>But here’s the catch: If your access pattern is too random, the prefetcher gives up. Instead of smoothly fetching data ahead of time, the CPU is left waiting, like someone stuck refreshing Google Maps on a broken internet connection or blind date.</p>
<p>This happens a lot with linked lists and hash tables, where memory jumps around unpredictably.</p>
<h4 id="heading-example-2">Example:</h4>
<pre><code class="lang-python"><span class="hljs-comment"># Linked list traversal (random memory jumps)  </span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>  
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, val</span>):</span>  
        self.val = val  
        self.next = <span class="hljs-literal">None</span>  

head = Node(<span class="hljs-number">0</span>)  
current = head  
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000</span>):  <span class="hljs-comment"># Each 'next' points to a random memory location  </span>
    current.next = Node(<span class="hljs-number">0</span>)  
    current = current.next  

<span class="hljs-comment"># Walking this list = 100,000 cache misses</span>
</code></pre>
<h4 id="heading-why-this-hurts">Why this hurts:</h4>
<p>Each time the CPU needs the next <code>Node</code>, it has to fetch it from a random memory location, making prefetching useless and causing frequent cache misses.</p>
<h3 id="heading-the-fix-use-contiguous-data-structures"><strong>The Fix: Use Contiguous Data Structures</strong></h3>
<p>Instead of using a linked list, store your data in a contiguous memory block (like an array or NumPy array). This way, the CPU can easily prefetch the next elements in sequence, speeding things up.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Array traversal (prefetcher-friendly)  </span>
data = [<span class="hljs-number">0</span>] * <span class="hljs-number">100000</span>  <span class="hljs-comment"># Contiguous memory  </span>
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> data:  
    <span class="hljs-keyword">pass</span>  <span class="hljs-comment"># CPU prefetches next elements seamlessly</span>
</code></pre>
<p><strong>Why this is better:</strong></p>
<ul>
<li><p>The CPU efficiently prefetches upcoming values instead of waiting.</p>
</li>
<li><p>Fewer cache misses = way faster execution.</p>
</li>
<li><p>Hot loops (loops that run millions of times) get a huge performance boost.</p>
</li>
</ul>
<p>📌 <strong>Hot loops</strong> are loops that execute a massive number of times, like those in data processing, AI models, and game engines. Even a small speedup in a hot loop can dramatically improve overall performance.</p>
<h3 id="heading-problem-2-the-invisible-tax-of-memory-pages-tlb-thrashing"><strong>Problem 2: The Invisible Tax of Memory Pages (TLB Thrashing)</strong></h3>
<h4 id="heading-what-you-think-happens-1">What you think happens:</h4>
<p><em>“My 10GB dataset is just… there. Accessing it is free, right?”</em></p>
<h4 id="heading-what-actually-happens-1">What actually happens:</h4>
<p>Your OS splits memory into 4KB pages. Every time your program accesses a new memory page, the CPU consults a Translation Lookaside Buffer (TLB)—a “phonebook” for fast page lookups.</p>
<p>If your program jumps between too many pages, you get TLB misses, and the CPU wastes cycles waiting for the OS to fetch memory mappings.</p>
<h4 id="heading-example-3">Example:</h4>
<pre><code class="lang-python"><span class="hljs-comment"># Iterating a giant list with random access  </span>
data = [x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>_000_000)]  
total = <span class="hljs-number">0</span>  
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> random_indexes:  <span class="hljs-comment"># 1,000,000 random jumps  </span>
    total += data[i]  <span class="hljs-comment"># Each jump likely hits a new page</span>
</code></pre>
<h4 id="heading-why-this-hurts-1">Why this hurts:</h4>
<ul>
<li><p>TLB misses can add 10-100 CPU cycles per access.</p>
</li>
<li><p>If you have millions of random accesses, that’s billions of wasted cycles.</p>
</li>
</ul>
<h3 id="heading-the-fix-process-data-in-chunks"><strong>The Fix: Process Data in Chunks</strong></h3>
<p>To reduce TLB misses:</p>
<ul>
<li><p><strong>Process data in chunks</strong> (for example, 4096 elements at a time) instead of randomly jumping around.</p>
</li>
<li><p><strong>Use huge pages</strong> (2MB instead of 4KB) so that more data fits in each memory page.</p>
</li>
</ul>
<h3 id="heading-problem-3-your-code-is-a-tourist-in-the-wrong-cpu-neighborhood-numa"><strong>Problem 3: Your Code is a Tourist in the Wrong CPU Neighborhood (NUMA)</strong></h3>
<h4 id="heading-what-you-think-happens-2">What you think happens:</h4>
<p><em>“My 64-core server is a speed paradise!”</em></p>
<h4 id="heading-what-actually-happens-2">What actually happens:</h4>
<p>On multi-socket servers, memory is divided into NUMA (Non-Uniform Memory Access) zones. Each CPU socket has its own local memory, and accessing memory from another socket is slow—like ordering Uber Eats from another city.</p>
<h4 id="heading-example-4">Example:</h4>
<pre><code class="lang-python"><span class="hljs-comment"># Running this on a 2-socket server:  </span>
<span class="hljs-keyword">from</span> multiprocessing <span class="hljs-keyword">import</span> Pool  
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np  

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process</span>(<span class="hljs-params">chunk</span>):</span>  
    data = np.load(<span class="hljs-string">"giant_array.npy"</span>)  <span class="hljs-comment"># Allocated on Socket 1's RAM  </span>
    <span class="hljs-keyword">return</span> chunk * data  <span class="hljs-comment"># If process runs on Socket 2's CPU... ouch  </span>

<span class="hljs-keyword">with</span> Pool(<span class="hljs-number">64</span>) <span class="hljs-keyword">as</span> p:  
    p.map(process, big_data)  <span class="hljs-comment"># 64 cores fighting over remote RAM</span>
</code></pre>
<h4 id="heading-why-this-hurts-2">Why this hurts:</h4>
<ul>
<li><p>Accessing memory from another NUMA zone can be 2-4x slower.</p>
</li>
<li><p>Your 64 cores end up waiting for memory instead of actually computing.</p>
</li>
</ul>
<h3 id="heading-the-fix-pin-processes-to-numa-aware-memory"><strong>The Fix: Pin Processes to NUMA-Aware Memory</strong></h3>
<p>Instead of letting your processes randomly access memory, you can pin them to the correct NUMA node.</p>
<ul>
<li><p>Use <code>numactl</code> on Linux to allocate memory near the CPU that will use it.</p>
</li>
<li><p>Use <code>numba</code>-aware libraries in NumPy to ensure data is allocated optimally.</p>
</li>
</ul>
<h3 id="heading-problem-4-the-cpu-is-a-drama-queen-speculative-execution"><strong>Problem 4: The CPU is a Drama Queen (Speculative Execution)</strong></h3>
<h4 id="heading-what-you-think-happens-3">What you think happens:</h4>
<p><em>“My code runs in the order I wrote it!”</em></p>
<h4 id="heading-what-actually-happens-3">What actually happens:</h4>
<p>CPUs speculatively execute code ahead of time. If they guess wrong, they have to rollback everything and restart, which slows things down.</p>
<h4 id="heading-example-5"><strong>Example:</strong></h4>
<pre><code class="lang-cpp"><span class="hljs-comment">// Unpredictable branches = CPU's worst nightmare  </span>
<span class="hljs-keyword">if</span> (rare_condition) {  <span class="hljs-comment">// 99% of the time, this is false  </span>
    do_work();  
}
</code></pre>
<h4 id="heading-why-this-hurts-3">Why this hurts:</h4>
<p>A branch misprediction wastes 15-20 cycles. In hot loops, this can really hurt performance.</p>
<h3 id="heading-the-fix-make-branches-predictable"><strong>The Fix: Make Branches Predictable</strong></h3>
<p>Sort data to help the CPU make better predictions:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Process all 'valid' items first, then 'invalid' ones  </span>
sorted_data = sorted(data, key=<span class="hljs-keyword">lambda</span> x: x.is_valid, reverse=<span class="hljs-literal">True</span>)  
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> sorted_data:  
    <span class="hljs-keyword">if</span> item.is_valid:  <span class="hljs-comment"># CPU learns the pattern → accurate predictions  </span>
        process(item)
</code></pre>
<p><strong>Why This Works:</strong></p>
<ul>
<li><p>Branching becomes predictable—the CPU stops guessing wrong.</p>
</li>
<li><p>Sorting ahead of time reduces rollbacks and wasted cycles.</p>
</li>
</ul>
<h3 id="heading-how-to-fight-back"><strong>How to Fight Back</strong></h3>
<p>Here’s how you can stop your CPU from sabotaging your code:</p>
<ol>
<li>Treat Memory Like a Highway: Cache lines matter. Keep data contiguous so the CPU doesn’t have to search for it.</li>
</ol>
<ol start="2">
<li><p>Profile with <code>perf</code>: Use Linux’s <code>perf</code> tool to spot cache misses, page faults, and TLB thrashing:</p>
<pre><code class="lang-bash"> perf <span class="hljs-built_in">stat</span> -e cache-misses,page-faults ./your_code
</code></pre>
</li>
</ol>
<ol start="3">
<li>Assume Nothing. Benchmark Everything: CPUs have a thousand undocumented behaviors. Test different data layouts, loop structures, and memory allocations to see what’s fastest.</li>
</ol>
<h2 id="heading-mistake-5-memory-fragmentation"><strong>Mistake #5: Memory Fragmentation</strong></h2>
<p>You’ve optimized your algorithms. You’ve nailed Big O. Yet your app still crashes with “out of memory” errors or slows to a crawl over time. The culprit? Memory fragmentation—a ghost in the machine that most developers ignore until it’s too late.</p>
<h4 id="heading-whats-happening-under-the-hood">What’s Happening Under the Hood</h4>
<p>When your code allocates and frees memory blocks of varying sizes, it leaves behind a patchwork of free and used spaces. Over time, this creates a Swiss cheese effect in your RAM: plenty of total free memory, but no contiguous blocks for new allocations.</p>
<p><strong>Example:</strong><br>Imagine a C++ server that handles requests by allocating buffers of random sizes:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">process_request</span><span class="hljs-params">()</span> </span>{  
    <span class="hljs-comment">// Allocate a buffer of random size between 1–1024 bytes  </span>
    <span class="hljs-keyword">char</span>* buffer = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[rand() % <span class="hljs-number">1024</span> + <span class="hljs-number">1</span>];  
    <span class="hljs-comment">// ... process ...  </span>
    <span class="hljs-keyword">delete</span>[] buffer;  
}
</code></pre>
<p>After millions of requests, your memory looks like this:</p>
<p><code>[USED][FREE][USED][FREE][USED][FREE]...</code></p>
<p>Now, when you try to allocate a 2KB buffer, it fails—not because there’s no space, but because no single free block is large enough.</p>
<h4 id="heading-how-to-fix-it-1">How to Fix it:</h4>
<p>Use a memory pool to allocate fixed-size blocks:</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MemoryPool</span> {</span>  
<span class="hljs-keyword">public</span>:  
    MemoryPool(<span class="hljs-keyword">size_t</span> block_size) : block_size_(block_size) {}  
    <span class="hljs-function"><span class="hljs-keyword">void</span>* <span class="hljs-title">allocate</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">/* get a pre-allocated block */</span> }  
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">deallocate</span><span class="hljs-params">(<span class="hljs-keyword">void</span>* ptr)</span> </span>{ <span class="hljs-comment">/* return block to pool */</span> }  
};  

<span class="hljs-comment">// All requests use buffers of fixed size (1024 bytes)  </span>
<span class="hljs-function">MemoryPool <span class="hljs-title">pool</span><span class="hljs-params">(<span class="hljs-number">1024</span>)</span></span>;  
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">process_request</span><span class="hljs-params">()</span> </span>{  
    <span class="hljs-keyword">char</span>* buffer = <span class="hljs-keyword">static_cast</span>&lt;<span class="hljs-keyword">char</span>*&gt;(pool.allocate());  
    <span class="hljs-comment">// ... process ...  </span>
    pool.deallocate(buffer);  
}
</code></pre>
<p>By standardizing block sizes, you eliminate fragmentation.</p>
<h3 id="heading-the-autoboxing-trap-java-c-and-so-on">The Autoboxing Trap (Java, C#, and so on)</h3>
<h4 id="heading-whats-happening">What’s Happening?</h4>
<p>In languages that mix primitives (like <code>int</code>, <code>float</code>) and objects (like <code>Integer</code>, <code>Double</code>), converting a primitive to its object wrapper is called <strong>autoboxing</strong>. It feels harmless, but in hot loops, it’s a performance disaster.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-java"><span class="hljs-comment">// Slow: Creates 1,000,000 Integer objects (and garbage!)</span>
List&lt;Integer&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1_000_000</span>; i++) {  
    list.add(i);  <span class="hljs-comment">// Autoboxing 'i' to Integer  </span>
}
</code></pre>
<h4 id="heading-why-this-hurts-performance">Why this hurts performance:</h4>
<ul>
<li><p><strong>Memory overhead:</strong> Each <code>Integer</code> object adds 16–24 bytes of extra memory (object headers, pointers). With 1,000,000 numbers, that’s an extra 16–24MB wasted just on overhead.</p>
</li>
<li><p><strong>Garbage collection (GC) pressure:</strong> Since objects are allocated on the heap, the GC constantly cleans up old <code>Integer</code> objects, leading to latency spikes.</p>
</li>
<li><p><strong>CPU cache inefficiency:</strong> Primitives like <code>int</code> are tightly packed in memory, but <code>Integer</code> objects are scattered across the heap with extra indirection, wrecking cache locality.</p>
</li>
</ul>
<h4 id="heading-the-fix-use-primitive-collections">The Fix: Use Primitive Collections</h4>
<p>To avoid autoboxing, use data structures that store raw primitives instead of objects. In Java, Eclipse Collections provides primitive-friendly lists like <code>IntList</code> that store raw <code>int</code> values directly.</p>
<p><strong>Example: The Faster Version (Primitive Collections)</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import primitive-friendly collection</span>
<span class="hljs-keyword">import</span> org.eclipse.collections.api.list.primitive.IntList;
<span class="hljs-keyword">import</span> org.eclipse.collections.impl.list.mutable.primitive.IntArrayList;  

<span class="hljs-comment">// Use IntArrayList to store raw ints</span>
IntList list = <span class="hljs-keyword">new</span> IntArrayList();  
<span class="hljs-keyword">for</span> (int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1</span>_000_000; i++) {  
    list.add(i);  <span class="hljs-comment">// No autoboxing! Stores raw 'int'  </span>
}
</code></pre>
<h4 id="heading-how-this-fix-works">How this fix works:</h4>
<ul>
<li><p>Stores raw <code>int</code> values instead of <code>Integer</code> objects, eliminating memory overhead.</p>
</li>
<li><p>Avoids heap allocations, so the garbage collector doesn’t get involved.</p>
</li>
<li><p>Keeps numbers tightly packed in memory, improving CPU cache efficiency.</p>
</li>
</ul>
<h4 id="heading-the-fix-for-c">The Fix for C</h4>
<p>In C#, you can avoid unnecessary heap allocations by using <code>struct</code>s and <code>Span&lt;T&gt;</code>, which keep data on the stack or in contiguous memory rather than the heap.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Span&lt;T&gt; avoids heap allocations  </span>
Span&lt;<span class="hljs-keyword">int</span>&gt; numbers = <span class="hljs-keyword">stackalloc</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">1</span>_000_000];  
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numbers.Length; i++) {  
    numbers[i] = i;  <span class="hljs-comment">// No boxing, no heap allocation  </span>
}
</code></pre>
<p>No object wrappers. No GC pressure. Just performance.</p>
<h2 id="heading-mistake-6-the-cache-catch"><strong>Mistake #6: The Cache (catch)</strong></h2>
<p>You’ve heard “cache matters,” but here’s the twist: your loops are lying to your CPU. The way you traverse multi-dimensional arrays can turn a 10x speed difference into a mystery that leaves you questioning reality.</p>
<h3 id="heading-row-major-vs-column-major-access"><strong>Row-Major vs. Column-Major Access</strong></h3>
<p><strong>What you think happens</strong>:<br><em>“Iterating over a 2D array is the same whether I go row-by-row or column-by-column. Right?”</em></p>
<p><strong>What actually happens</strong>:<br>Memory is laid out linearly, but CPUs prefetch data in chunks (cache lines). Traversing against the grain forces the CPU to fetch new cache lines <em>every single step</em>.</p>
<p><strong>Example in C</strong>:</p>
<pre><code class="lang-c"><span class="hljs-comment">// A "tiny" 1024x1024 matrix  </span>
<span class="hljs-keyword">int</span> matrix[<span class="hljs-number">1024</span>][<span class="hljs-number">1024</span>];  

<span class="hljs-comment">// Fast: Row-major traversal (cache-friendly)  </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1024</span>; i++) {  
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">1024</span>; j++) {  
        matrix[i][j] = i + j;  
    }  
}  

<span class="hljs-comment">// Slow: Column-major traversal (cache-hostile)  </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">1024</span>; j++) {  
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1024</span>; i++) {  
        matrix[i][j] = i + j;  
    }  
}
</code></pre>
<p><strong>The result</strong>:</p>
<ul>
<li><p>Row-major: ~5ms (data flows like a river).</p>
</li>
<li><p>Column-major: ~50ms (CPU drowns in cache misses).</p>
</li>
</ul>
<p><strong>Why it’s worse than you think</strong>:<br>In C/C++, arrays are row-major. But in Fortran, MATLAB, or Julia, they’re column-major. Use the wrong traversal order in these languages, and you’ll get the same penalty.</p>
<h3 id="heading-the-plot-twist-your-programming-language-is-gaslighting-you"><strong>The Pl**</strong>ot Twist: Your Programming Language is Gaslighting You**</h3>
<p>In C and Python (NumPy default), arrays use row-major order. But in Fortran, MATLAB, and Julia, arrays are column-major. If you assume the wrong layout, your loops will be slow for no apparent reason.</p>
<p><strong>Python Example</strong>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np  

<span class="hljs-comment"># Row-major (C-style) → Fast for row-wise loops  </span>
row_major = np.zeros((<span class="hljs-number">1024</span>, <span class="hljs-number">1024</span>), order=<span class="hljs-string">'C'</span>)  

<span class="hljs-comment"># Column-major (Fortran-style) → Fast for column-wise loops  </span>
col_major = np.zeros((<span class="hljs-number">1024</span>, <span class="hljs-number">1024</span>), order=<span class="hljs-string">'F'</span>)  

<span class="hljs-comment"># ❌ Slow: Column-wise access on a row-major array  </span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1024</span>):  
    <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">1024</span>):  
        col_major[i][j] = i + j  <span class="hljs-comment"># Cache-miss chaos!</span>
</code></pre>
<h4 id="heading-why-this-is-a-problem-3">Why this is a problem:</h4>
<ul>
<li><p>Row-major (default in NumPy) expects row-wise access, but the loop accesses it column-wise, causing cache misses.</p>
</li>
<li><p>Fortran-style arrays are stored column-first, so row-wise loops will be slow instead.</p>
</li>
</ul>
<h4 id="heading-the-fix">The Fix:</h4>
<ul>
<li><p>Match the array order to your access pattern using <code>order='C'</code> (row-major) or <code>order='F'</code> (column-major).</p>
</li>
<li><p>Convert data layout with <code>np.asarray()</code> if needed.</p>
</li>
</ul>
<h3 id="heading-the-multidimensional-illusion-3d-arrays"><strong>The Multidimensional Illusion**</strong>: 3D+ Arrays**</h3>
<p><strong>What you think happens</strong>:<br><em>“3D arrays are just 2D arrays with extra steps. No big deal.”</em></p>
<p><strong>What actually happens</strong>:<br>Each dimension adds a layer of indirection. A 3D array in C is an array of arrays of arrays. Traversing the “wrong” dimension forces the CPU to dereference pointers repeatedly, killing locality.</p>
<p><strong>Example</strong>: 3D Array in Traversal in C</p>
<pre><code class="lang-c"><span class="hljs-comment">// ✅ Fast: Iterate in Row-Major Order (Innermost Dimension Last)</span>

<span class="hljs-keyword">int</span> space[<span class="hljs-number">256</span>][<span class="hljs-number">256</span>][<span class="hljs-number">256</span>];  

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">256</span>; x++) {  
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> y = <span class="hljs-number">0</span>; y &lt; <span class="hljs-number">256</span>; y++) {  
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> z = <span class="hljs-number">0</span>; z &lt; <span class="hljs-number">256</span>; z++) {  
            space[x][y][z] = x + y + z;  <span class="hljs-comment">// Smooth memory access  </span>
        }  
    }  
}
</code></pre>
<p>So what happens is that the innermost loop moves through contiguous memory, making full use of cache lines.</p>
<pre><code class="lang-c"><span class="hljs-comment">// ❌ Slow: Iterate in the Wrong Order (Innermost Dimension First)</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> z = <span class="hljs-number">0</span>; z &lt; <span class="hljs-number">256</span>; z++) {  
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> y = <span class="hljs-number">0</span>; y &lt; <span class="hljs-number">256</span>; y++) {  
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">256</span>; x++) {  
            space[x][y][z] = x + y + z;  <span class="hljs-comment">// Constant cache misses  </span>
        }  
    }  
}
</code></pre>
<p><strong>Why this is bad</strong>:</p>
<ul>
<li><p>This loop jumps across memory every time <code>x</code> changes.</p>
</li>
<li><p>Instead of accessing contiguous memory, it dereferences pointers constantly.</p>
</li>
<li><p>Penalty: Up to 100x slower for large 3D arrays!</p>
</li>
</ul>
<h3 id="heading-the-nuclear-option-cache-aware-algorithms"><strong>The Nuclear Option: Cache-Aware Algorithms</strong></h3>
<p>For extreme performance (game engines, HPC), you need to design for cache lines:</p>
<ol>
<li><p><strong>Tiling</strong>: Split arrays into small blocks that fit in L1/L2 cache.</p>
<pre><code class="lang-python"> // Process <span class="hljs-number">8</span>x8 tiles to exploit <span class="hljs-number">64</span>-byte cache lines  
 <span class="hljs-keyword">for</span> (int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1024</span>; i += <span class="hljs-number">8</span>) {  
     <span class="hljs-keyword">for</span> (int j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">1024</span>; j += <span class="hljs-number">8</span>) {  
         // Process tile[i:i+<span class="hljs-number">8</span>][j:j+<span class="hljs-number">8</span>]  
     }  
 }
</code></pre>
</li>
<li><p><strong>SoA vs. AoS</strong>: Prefer Structure of Arrays (SoA) over Array of Structures for SIMD.</p>
<pre><code class="lang-python"> // Slow: Array of Structures (AoS)  
 struct Particle { float x, y, z; };  
 Particle particles[<span class="hljs-number">1000000</span>];  

 // Fast: Structure of Arrays (SoA)  
 struct Particles {  
     float x[<span class="hljs-number">1000000</span>];  
     float y[<span class="hljs-number">1000000</span>];  
     float z[<span class="hljs-number">1000000</span>];  
 };
</code></pre>
</li>
</ol>
<h2 id="heading-mistake-7-the-copy-paste-trap"><strong>Mistake #7: The Copy-Paste Trap</strong></h2>
<p>You’d never download 10 copies of the same movie. But in code? You’re probably cloning data <em>all the time</em> without realizing it. Here’s how invisible copies turn your app into a bloated, slow mess—and how to fix it.</p>
<h3 id="heading-problem-1-the-ghost-copies-in-harmless-operations"><strong>Problem 1: The Ghost Copies in “Harmless” Operations</strong></h3>
<p><strong>What you think happens</strong>:<br><em>“I sliced a list—it’s just a reference, right?”</em></p>
<p><strong>What actually happens</strong>:<br>In many languages, slicing creates a full copy of the data. Do this with large datasets, and you’re silently doubling memory usage and CPU work.</p>
<p><strong>Python Example</strong>:</p>
<pre><code class="lang-python"><span class="hljs-comment"># A 1GB list of data  </span>
big_data = [ ... ]  <span class="hljs-comment"># 1,000,000 elements  </span>

<span class="hljs-comment"># Accidentally cloning the entire list  </span>
snippet = big_data[:<span class="hljs-number">1000</span>]  <span class="hljs-comment"># Creates a copy (harmless, right?)  </span>

<span class="hljs-comment"># Better: Use a view (if possible)  </span>
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np  
big_array = np.array(big_data)  
snippet = big_array[:<span class="hljs-number">1000</span>]  <span class="hljs-comment"># A view, not a copy (0MB added)</span>
</code></pre>
<h4 id="heading-why-this-hurts-4">Why this hurts:</h4>
<ul>
<li><p>Copying 1GB → 2GB of RAM used.</p>
</li>
<li><p>If this happens in a loop, your program could crash with <code>MemoryError</code>.</p>
</li>
</ul>
<h4 id="heading-the-fix-1">The Fix:</h4>
<ul>
<li><p>Use memory views (<code>numpy</code>, <code>memoryview</code> in Python) or lazy slicing (Pandas <code>.iloc</code>).</p>
</li>
<li><p>In JavaScript, <code>slice()</code> copies arrays—replace with <code>TypedArray.subarray</code> for buffers.</p>
</li>
</ul>
<h3 id="heading-problem-2-the-hidden-cost-of-functional-code"><strong>Problem 2: The Hidden Cost of “Functional” Code</strong></h3>
<h4 id="heading-what-you-think-happens-4">What you think happens:</h4>
<p><em>“I’ll chain array methods for clean, readable code!”</em></p>
<h4 id="heading-what-actually-happens-4">What actually happens:</h4>
<p>Every <code>map</code>, <code>filter</code>, or <code>slice</code> creates a new array. Chain three operations? You’ve cloned your data three times.</p>
<p><strong>JavaScript Example</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// A 10,000-element array  </span>
<span class="hljs-keyword">const</span> data = [ ... ];  

<span class="hljs-comment">// Slow: Creates 3 copies (original → filtered → mapped → sliced)  </span>
<span class="hljs-keyword">const</span> result = data  
  .filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x.active)  
  .map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x.value * <span class="hljs-number">2</span>)  
  .slice(<span class="hljs-number">0</span>, <span class="hljs-number">100</span>);  

<span class="hljs-comment">// Faster: Do it in one pass  </span>
<span class="hljs-keyword">const</span> result = [];  
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; data.length; i++) {  
  <span class="hljs-keyword">if</span> (data[i].active) {  
    result.push(data[i].value * <span class="hljs-number">2</span>);  
    <span class="hljs-keyword">if</span> (result.length === <span class="hljs-number">100</span>) <span class="hljs-keyword">break</span>;  
  }  
}
</code></pre>
<p><strong>Why this hurts</strong>:</p>
<ul>
<li><p>10,000 elements → 30,000 operations + 3x memory.</p>
</li>
<li><p>Functional programming is <em>elegant</em> but can be <em>expensive</em>.</p>
</li>
</ul>
<h4 id="heading-the-fix-2">The Fix:</h4>
<ul>
<li><p>Use generators (Python <code>yield</code>, JS <code>function*</code>) for lazy processing.</p>
</li>
<li><p>Replace method chains with single-pass loops in hot paths.</p>
</li>
</ul>
<h3 id="heading-problem-3-the-ill-just-modify-a-copy-mistake"><strong>Problem 3: The “I’ll Just Modify a Copy” Mistake</strong></h3>
<p><strong>What you think happens</strong>:<br><em>“I need to tweak this object. I’ll duplicate it to avoid side effects.”</em></p>
<p><strong>What actually happens</strong>:<br>Deep cloning complex objects (especially in loops) is like photocopying a dictionary every time you edit a word.</p>
<p><strong>Python Example</strong>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> copy  

config = {<span class="hljs-string">"theme"</span>: <span class="hljs-string">"dark"</span>, <span class="hljs-string">"settings"</span>: { ... }}  <span class="hljs-comment"># Nested data  </span>

<span class="hljs-comment"># Slow: Deep-copying before every edit  </span>
<span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users:  
    user_config = copy.deepcopy(config)  <span class="hljs-comment"># Copies entire nested structure  </span>
    user_config[<span class="hljs-string">"theme"</span>] = user.preference  
    <span class="hljs-comment"># ...  </span>

<span class="hljs-comment"># Faster: Reuse the base config, overlay changes  </span>
<span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users:  
    user_config = {<span class="hljs-string">"theme"</span>: user.preference, **config}  <span class="hljs-comment"># Shallow merge  </span>
    <span class="hljs-comment"># ...</span>
</code></pre>
<p><strong>Why this hurts</strong>:</p>
<ul>
<li><p><code>deepcopy</code> is 10-100x slower than shallow copies.</p>
</li>
<li><p>Multiplied by 1,000 users, you’re wasting minutes.</p>
</li>
</ul>
<h4 id="heading-the-fix-3">The Fix:</h4>
<ul>
<li><p>Use immutable patterns: Create new objects by merging instead of cloning.</p>
</li>
<li><p>For big data, use structural sharing (libraries like <code>immutables</code> in Python).</p>
</li>
</ul>
<h3 id="heading-how-to-escape-the-copy-paste-hell"><strong>How to Escape the Copy-Paste hell?</strong></h3>
<ol>
<li><p><strong>Ask: “Do I need a copy?”</strong>: 90% of the time, you don’t. Use views, generators, or in-place edits.</p>
</li>
<li><p><strong>Profile memory usage</strong>: Tools like <code>memory_profiler</code> (Python) or Chrome DevTools (JS) show copy overhead.</p>
</li>
<li><p><strong>Learn your language’s quirks</strong>:</p>
<ul>
<li><p>Python: Slicing lists copies, slicing NumPy arrays doesn’t.</p>
</li>
<li><p>JavaScript: <code>[...array]</code> clones, <code>array.subarray</code> (TypedArray) doesn’t.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-how-do-pro-developers-write-faster-code">How Do Pro Developers Write Faster Code?</h2>
<p>Most beginners think "fast code" just means writing cleaner syntax or using a different framework. But in reality, performance isn't just about what language or framework you use—it's about how you think.</p>
<p>Pro developers don’t just write code. They measure, test, and optimize it<strong>.</strong> Here’s how they do it.</p>
<h3 id="heading-1-they-profile-their-code-instead-of-guessing"><strong>1. They Profile Their Code Instead of Guessing</strong></h3>
<p>🔥 Beginners: “This function feels slow… maybe I should rewrite it?”<br>💡 Pros: “Let’s profile it and see what’s actually slow.”</p>
<p>Instead of randomly rewriting code, pro developers measure first using <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-pythons-built-in-profiling-tools-examples-and-best-practices/">profiling tools</a>.</p>
<p><strong>Example:</strong> In Python, you can use <code>cProfile</code> to analyze where your code is spending the most time:</p>
<pre><code class="lang-javascript">pythonCopyEditimport cProfile

def slow_function():
    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>**<span class="hljs-number">6</span>):
        total += i
    <span class="hljs-keyword">return</span> total

cProfile.run(<span class="hljs-string">'slow_function()'</span>)
</code></pre>
<p>👀 <strong>What this tells you:</strong></p>
<ul>
<li><p>Which function takes the longest</p>
</li>
<li><p>How many times is a function being called</p>
</li>
<li><p>Where is the actual bottleneck</p>
</li>
</ul>
<p>✅ <strong>Takeaway:</strong> Before optimizing, always profile your code. You can’t fix what you don’t measure.</p>
<p>Other useful tools:</p>
<ul>
<li><p><strong>Python:</strong> <code>cProfile</code>, <code>line_profiler</code></p>
</li>
<li><p><strong>JavaScript:</strong> Chrome DevTools Performance Tab</p>
</li>
<li><p><strong>Java:</strong> JProfiler</p>
</li>
<li><p><strong>General:</strong> <code>perf</code>, <code>Valgrind</code></p>
</li>
</ul>
<h3 id="heading-2-they-avoid-premature-optimization"><strong>2. They Avoid Premature Optimization</strong></h3>
<p>🔥 Beginners: “I’ll spend hours optimizing this loop before testing it.”<br>💡 Pros: “I’ll make it work first, then optimize only what matters.”</p>
<p>Donald Knuth famously said, <em>"Premature optimization is the root of all evil."</em> Many beginners waste time optimizing things that aren’t actually slow.</p>
<p><strong>Example:</strong> A beginner might spend hours optimizing a loop that runs in 0.001 seconds, while the real slowdown is an extra database query that takes 500ms.</p>
<p>✅ <strong>Takeaway:</strong></p>
<ul>
<li><p>First, make your code work.</p>
</li>
<li><p>Then, profile and optimize only what’s slow.</p>
</li>
</ul>
<h3 id="heading-3-they-pick-the-right-data-structures-not-just-whats-familiar"><strong>3. They Pick the Right Data Structures (Not Just What’s Familiar)</strong></h3>
<p>🔥 Beginners: “I’ll just use a list.”<br>💡 Pros: “Which data structure is optimal for this task?”</p>
<p>Most slowdowns happen because of bad data structure choices. Pro developers pick the right tool instead of just going with the default.</p>
<p><strong>Example: Fast lookups</strong><br>❌ <strong>Slow (List - O(n))</strong></p>
<pre><code class="lang-javascript">pythonCopyEditusers = [<span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>, <span class="hljs-string">"charlie"</span>]
<span class="hljs-keyword">if</span> <span class="hljs-string">"bob"</span> <span class="hljs-keyword">in</span> users:  # Searches the entire list
    print(<span class="hljs-string">"Found"</span>)
</code></pre>
<p>✅ <strong>Fast (Set - O(1))</strong></p>
<pre><code class="lang-javascript">pythonCopyEditusers = {<span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>, <span class="hljs-string">"charlie"</span>}
<span class="hljs-keyword">if</span> <span class="hljs-string">"bob"</span> <span class="hljs-keyword">in</span> users:  # Uses a hash table <span class="hljs-keyword">for</span> instant lookup
    print(<span class="hljs-string">"Found"</span>)
</code></pre>
<p>✅ <strong>Takeaway:</strong> When performance matters, choose the right data structure, not just the most familiar one.</p>
<h3 id="heading-4-they-automate-performance-checks"><strong>4. They Automate Performance Checks</strong></h3>
<p>🔥 Beginners: “I’ll check for performance issues when I feel like it.”<br>💡 Pros: “I’ll use tools to automatically catch performance bottlenecks.”</p>
<p>Instead of manually looking for slow code, pro developers rely on automated tools that flag inefficiencies.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p><strong>Python:</strong> <code>py-spy</code> (lightweight sampling profiler)</p>
</li>
<li><p><strong>JavaScript:</strong> Chrome DevTools Performance Monitoring</p>
</li>
<li><p><strong>Java:</strong> JMH (Java Microbenchmark Harness)</p>
</li>
<li><p><strong>AI-assisted code reviews:</strong> There are tools like <a target="_blank" href="http://codeant.ai">CodeAnt</a> that analyze and auto fix your code automatically when you push on GitHub(or anywhere) and suggest performance improvements.</p>
</li>
</ul>
<p>✅ <strong>Takeaway:</strong> Set up automated checks so you catch performance issues early—before they hit production.</p>
<h3 id="heading-5-they-think-about-performance-from-day-one"><strong>5. They Think About Performance From Day One</strong></h3>
<p>🔥 Beginners: “I’ll optimize later.”<br>💡 Pros: “I’ll write efficient code from the start.”</p>
<p>While premature optimization is bad, writing slow code from the start is worse. Pro developers avoid common pitfalls before they become real problems.</p>
<p><strong>Example: Writing efficient loops from the start</strong><br>❌ <strong>Slow (Unnecessary</strong> <code>.append()</code>)</p>
<pre><code class="lang-javascript">pythonCopyEditresult = []
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>**<span class="hljs-number">6</span>):
    result.append(i * <span class="hljs-number">2</span>)  # This is slow
</code></pre>
<p>✅ <strong>Fast (List Comprehension - Optimized from the Start)</strong></p>
<pre><code class="lang-javascript">pythonCopyEditresult = [i * <span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>**<span class="hljs-number">6</span>)]  # Faster, more efficient
</code></pre>
<p>✅ <strong>Takeaway:</strong> Small choices add up. Think about performance as you write, rather than fixing it later.</p>
<h3 id="heading-final-thoughts-lessons-learned-the-hard-way"><strong>🚀 Final Thoughts: Lessons Learned the Hard Way</strong></h3>
<p>Thanks for reading! These are some of the tips I’ve personally bookmarked for myself—things I’ve learned the hard way while coding, talking to dev friends, and working on real projects.</p>
<p>When I first started, I used to guess why my code was slow instead of measuring. I’d optimize random parts of my code and still wonder why things weren’t getting faster. Over time, I realized that pro developers don’t just “write fast code” by instinct—they use tools, measure, and optimize what actually matters.</p>
<p>I wrote this to save you from making the same mistakes I did. Hopefully, now you have a clearer roadmap to writing faster, more efficient code—without the frustration I went through! 🚀</p>
<p>If you found this helpful, bookmark it for later, and feel free to share it with a fellow dev who might be struggling with slow code too.</p>
<p>Happy coding! 😊</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Lightweight Linux Distributions For Older PCs ]]>
                </title>
                <description>
                    <![CDATA[ Do you have an old computer that’s showing its age but you still want to get some use out of it? Don't throw it out just yet!  There are lightweight Linux distributions designed to breathe new life into older hardware. These operating systems are str... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/lightweight-linux-distributions-for-your-pc/</link>
                <guid isPermaLink="false">66c861a551f56da58aee7b7e</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Thu, 13 Jul 2023 15:37:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/lukas-NLSXFjl_nhc-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Do you have an old computer that’s showing its age but you still want to get some use out of it? Don't throw it out just yet! </p>
<p>There are lightweight Linux distributions designed to breathe new life into older hardware. These operating systems are streamlined to use limited system resources while still providing a smooth user experience.</p>
<p>Here are some lightweight Linux distros we'll discuss in this article: </p>
<ul>
<li>Puppy Linux.</li>
<li>Bodhi Linux.</li>
<li>Peppermint OS.</li>
<li>AntiX.</li>
<li>Lubuntu.</li>
</ul>
<h2 id="heading-why-choose-a-lightweight-linux-distro">Why Choose a Lightweight Linux Distro?</h2>
<p>If your old PC is struggling to keep up with modern operating systems and software, it may be time to consider a lightweight Linux distro. These streamlined OS options are designed to run well on older and lower-spec hardware.</p>
<p>Why choose a lightweight distro? For starters, it will breathe new life into your old PC. Tasks like web browsing, emailing, and basic productivity will run smoothly again without lag or freezing.</p>
<p>Lightweight Linux distros are perfect for:</p>
<ul>
<li><strong>Old laptops</strong> - Give that aging laptop a second lease on life. A lightweight OS can make it usable again for on-the-go work and play.</li>
<li><strong>Netbooks</strong> - Underpowered netbooks will benefit greatly from a minimalist Linux distro. You'll be amazed how much more you can do.</li>
<li><strong>Secondary PCs</strong> - For a spare system or kids' computer, a lightweight distro is ideal. No need for expensive, power-hungry software.</li>
<li><strong>Learning Linux</strong> - If you're new to Linux, a lightweight distro with simple interface is easy to get started with. You can focus on learning the operating system without fancy extras getting in the way.</li>
</ul>
<p>With options like Bodhi, Peppermint OS, and AntiX, there's a lightweight Linux distro for every skill level and need. And since they're open source, the price is right — free! </p>
<h2 id="heading-puppy-linux-small-but-mighty">Puppy Linux: Small but Mighty</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-38.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image credit – PuppyLinux Official</em></p>
<p>If you have an older PC that's low on resources, <a target="_blank" href="https://puppylinux.com/">Puppy Linux</a> is a great lightweight distro to try. This tiny OS weighs in at under 300MB, so it can run smoothly even on systems with as little as 512MB of RAM.</p>
<p>Despite its small size, Puppy Linux packs a punch. It comes bundled with essential apps like a word processor, spreadsheet software, a web browser, and more. You'll have everything you need to be productive right out of the box.</p>
<p>Puppy Linux is also extremely flexible. You have the option to run it directly from RAM, which will make the system fly even on the oldest hardware. You can also install it to a USB drive, or internal hard drive, or even save your settings and files on the cloud.</p>
<p>This distro may be small in size, but it's big on customization. You can choose from a variety of window managers, desktop environments, and themes to make the interface look and work the way you want. You can also install thousands of additional packages from the Puppy and Ubuntu software repositories.</p>
<p>Whether you just want to breathe new life into an aging PC or experiment with Linux, Puppy is a perfect choice. Its tiny footprint, solid software selection, and extreme customizability makes it a small but mighty distro that can run well even on systems that have long been forgotten. Give your old PC a new leash on life with <a target="_blank" href="https://puppylinux.com/">Puppy Linux</a>.</p>
<h2 id="heading-bodhi-linux-enlightened-and-extra-light">Bodhi Linux: Enlightened and Extra Light</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-39.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image Credit – BodhiLinux Official</em></p>
<p>If you’re looking for an OS that will run smoothly on aging hardware without sacrificing functionality, <a target="_blank" href="https://www.bodhilinux.com/">Bodhi Linux</a> is a great choice. Bodhi is a lightweight Linux distribution based on Ubuntu that uses the Moksha desktop environment. It has a minimalistic yet elegant feel that’s perfect for older PCs.</p>
<p>Bodhi comes with only the essential apps pre-installed so you have full control over what runs on your system. You can choose from thousands of free software packages in the Bodhi repository using the built-in app center. Despite its lightweight nature, Bodhi supports thousands of Ubuntu packages, so you’ll have access to a wide range of software.</p>
<p>One of the best parts of Bodhi is how customizable it is. You can change desktop themes, icons, and more with just a few clicks. If there’s something you don’t like about the default setup, chances are that you can tweak it to your liking. The Enlightenment desktop environment that Bodhi is based on is highly modular, so you have a lot of flexibility.</p>
<p>Bodhi is available for both 32-bit and 64-bit systems, so no matter what type of PC you have, there’s a version that will work for you. System requirements are just 512MB of RAM and a 500MHz processor. Just lightweight.</p>
<p>If you want to breathe new life into an older laptop or desktop, Bodhi Linux is a perfect choice. With its minimal system requirements, elegant interface, and highly customizable nature, Bodhi will run well on older hardware while giving you a modern Linux experience. </p>
<p>Give <a target="_blank" href="https://www.bodhilinux.com/">Bodhi</a> a try and enjoy an “enlightened” computing experience on your PC.</p>
<h2 id="heading-peppermint-os-refreshingly-lightweight">Peppermint OS: Refreshingly Lightweight</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-40.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image Credit – PeppermintOS Official</em></p>
<p><a target="_blank" href="https://peppermintos.com/">Peppermint OS</a> is a lightweight Linux distro designed for older PCs and laptops. If your aging hardware is struggling under the weight of Windows or macOS, Peppermint could give it a new lease on life.</p>
<p>Here are some of its features:</p>
<h3 id="heading-light-on-resources">Light on Resources</h3>
<p>Peppermint OS uses the <a target="_blank" href="http://lxde.org/">LXDE</a> desktop environment that’s optimized for older CPUs and limited memory. It only needs 512MB of RAM to run, so it will fly on that Pentium 4 machine or Core 2 Duo laptop you have stashed in your closet. </p>
<p>The OS takes up about 3GB of storage. This keeps your system resources focused on the tasks that matter to you.</p>
<h3 id="heading-cloud-support">Cloud Support</h3>
<p>While Peppermint OS is light on local resources, it integrates well with cloud and web apps. The OS builds in close integration with services like Dropbox, Google Drive, and more. </p>
<p>You can save files directly to and open files from these cloud services. This means you have access to lots of functionality without needing high-powered local software.</p>
<h3 id="heading-user-friendly">User-Friendly</h3>
<p>Don’t worry if you’re not a Linux expert, Peppermint OS is designed to be easy to use. The menu is simple to navigate, and installing software is straightforward. </p>
<p>The distro is also compatible with lots of Windows programs, so you may be able to use some of the same software you’re familiar with.</p>
<p>The best part is that <a target="_blank" href="https://peppermintos.com/">Peppermint OS</a> is free to download and try. You can install it on your aging PC to give it a boost and see how it runs without committing to anything. If you find it’s not for you, you can simply uninstall it and you’re back to where you started. </p>
<p>For a PC that’s losing its charm, Peppermint OS could be just the refresh it needs. Why not give it a go?</p>
<h2 id="heading-antix-as-lean-as-they-come">AntiX: As Lean as They Come</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-41.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image Credit – ItsFoss</em></p>
<p>If you have an older PC that struggles with modern software, <a target="_blank" href="https://antixlinux.com/">AntiX</a> is an excellent lightweight Linux distro to try. AntiX is designed to run on systems with as little as 64MB of RAM and a Pentium II processor. Despite these minimal requirements, AntiX provides a complete desktop experience.</p>
<p><a target="_blank" href="https://antixlinux.com/">AntiX</a> uses the <a target="_blank" href="https://ice-wm.org/">IceWM window manager</a> and lightweight alternatives to popular software. The Claws email client, <a target="_blank" href="https://speechify.com/product-reviews/abiword/">AbiWord</a> word processor, and <a target="_blank" href="https://mtpaint.sourceforge.net/">mtPaint</a> are also included. AntiX also has its own lightweight system tools for things like managing users, networks, and services.</p>
<p>You should know these before using the AntiX distro:</p>
<ul>
<li>AntiX is based on <a target="_blank" href="https://www.debian.org/">Debian</a>, so the package management and repositories will feel familiar to most Linux users.</li>
<li>The AntiX ISO is under 700MB, so it’s quick to download and install.</li>
<li>AntiX is highly configurable. You can easily add and remove components to suit your needs.</li>
<li>AntiX releases are rolling, so you get continuous updates without needing to install a new version.</li>
</ul>
<p>AntiX is ideal if you want to give new life to that old PC collecting dust in your closet. It will run smoothly on systems that struggle with Windows and most mainstream Linux distributions. The minimal requirements mean it can work with nearly any x86 computer from the last 20 years.</p>
<p>Despite its lightweight nature, <a target="_blank" href="https://antixlinux.com/">AntiX</a> provides a complete desktop experience with office tools, internet apps, multimedia players, and more. If raw performance and responsiveness are your top priorities, AntiX is one of the best Linux distributions available for vintage PCs and older hardware.</p>
<h2 id="heading-lubuntu">Lubuntu</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-42.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image Credit – Wikipedia</em></p>
<p>If you’re looking for an Ubuntu-based distro that’s lightweight enough for older PCs, <a target="_blank" href="https://lubuntu.me/">Lubuntu</a> is a great choice. It uses the <a target="_blank" href="http://lxde.org/">LXDE</a> desktop environment which is super lightweight yet still user-friendly.</p>
<p><a target="_blank" href="https://lubuntu.me/">Lubuntu</a> will run smoothly on computers with as little as 512 MB of RAM and a 1 GHz processor. This makes it ideal for breathing new life into older laptops or desktops. The interface is simple but attractive, with lots of customization options if you want to tweak it.</p>
<ul>
<li>Software selection: Lubuntu comes with a basic set of apps for web browsing, office tasks, and more. You can always install more software from the Ubuntu repos which contains thousands of options.</li>
<li>Easy to use: The LXDE desktop is designed to be straightforward to navigate, even for Linux newbies. Things are laid out in an intuitive, familiar way.</li>
<li>Great community support: As an official Ubuntu flavor, Lubuntu receives continuous security and software updates. The large Ubuntu community can also provide help if you get stuck.</li>
</ul>
<p>Whether you just want to experiment with Linux or hope to give your old PC a speed boost, <a target="_blank" href="https://lubuntu.me/">Lubuntu</a> is worth checking out. </p>
<p>You can test it out by downloading the ISO and running the live session from a USB drive before doing a full install. With a lightweight yet capable distro like Lubuntu, that old hardware of yours has years of life left!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it, five Linux options that will breathe new life into your older PC without demanding too much from it. Any of these lightweight yet fully functional Linux distributions would be a great way to extend the useful life of your aging hardware.</p>
<p>Give one a try, see how it runs, and you might just fall in love with the speed and simplicity. Your old computer has more to offer, so set it free with a lightweight OS and enjoy hassle-free computing once again.</p>
<p>What are you waiting for? Pick a distro, back up your files, and take your vintage PC for a spin.</p>
<p>Thank you for reading. Happy Exploring. </p>
<p>I am <a target="_blank" href="https://rahul.biz">Rahul</a>, 19, Hustler. I am building <a target="_blank" href="https://fueler.io/register?referral_token=94329340-3e14-4e1e-83fa-bd5e1992">Fueler.io</a>, a platform for generalists to create proof of work profile and land opportunities. Let’s connect on <a target="_blank" href="https://twitter.com/rahul_wip">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Helpful Linux Commands You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Ever feel like you’ve mastered the basics of Linux and are ready to level up your skills? Well, good news – there are many powerful commands that you might not know about. In this article, I'll introduce you to some lesser-known Linux commands that w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/helpful-linux-commands-you-should-know/</link>
                <guid isPermaLink="false">66c8619c74f6ae8759515601</guid>
                
                    <category>
                        <![CDATA[ command line ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Mon, 03 Jul 2023 20:36:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/gabriel-heinzer-4Mw7nkQDByk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ever feel like you’ve mastered the basics of Linux and are ready to level up your skills? Well, good news – there are many powerful commands that you might not know about.</p>
<p>In this article, I'll introduce you to some lesser-known Linux commands that will help you become a more productive and effective developer.</p>
<p>Whether you’re looking to boost your productivity, tighten system security, or just want to show off your Linux chops to fellow devs, these commands have you covered.</p>
<h2 id="heading-chroot-run-commands-with-a-different-root-directory">Chroot: Run Commands With a Different Root Directory</h2>
<p>Ever wanted to run commands in a different root directory? The chroot command allows you to do just that.</p>
<p>Chroot, short for “<em>change root</em>,” lets you run commands with a different root directory. So if you wanted to test out software in a contained environment or build a minimal Linux system, chroot is your friend.</p>
<p>To use chroot, first you’ll need to set up a directory to act as the new root. Then you run the chroot command, passing it the path to that directory. For example, to chroot into <strong>/home/testdir,</strong> you’d run:</p>
<pre><code class="lang-bash">chroot /home/testdir
</code></pre>
<p>After that, any commands you run will be relative to / in the <code>/home/testdir directory</code>. So you could install packages, run shell scripts, compile programs, and so on. When you’re done, just exit the chroot with <code>exit</code>.</p>
<p>Chroot creates an isolated environment, so any changes you make won’t affect the rest of your system. It’s a handy <strong>tool for testing and development or for emergency recovery</strong>. Once you get familiar with chroot, you’ll find all sorts of uses for it.</p>
<h2 id="heading-crontab-schedule-tasks-to-run-automatically">Crontab: Schedule Tasks to Run Automatically</h2>
<p>Crontab is a handy Linux command that lets you schedule tasks to run automatically at specific times. You’ll wonder how you ever lived without it!</p>
<p>To get started, open the crontab file with <code>crontab -e</code>. This will open your default text editor where you can create schedule entries, called <a target="_blank" href="https://www.freecodecamp.org/news/cron-jobs-in-linux/">cron jobs</a>. Each entry has five-time fields – minute, hour, day of month, month, day of week, followed by the command to run.</p>
<p>For example, <code>0 0 * * * /home/user/daily_script.sh</code> would run the <strong>daily_script.sh</strong> script at midnight every day. You can also do <code>30 8 * * 1-5 /home/user/work_script.sh</code> to run <strong>work_script.sh</strong> at 8:30am every weekday.</p>
<p>Crontab allows a ton of flexibility. You can schedule jobs to run:</p>
<ul>
<li>Minutely, hourly, daily, weekly, monthly or yearly</li>
<li>At a specific minute/hour</li>
<li>On certain days of the week/month</li>
<li>With wildcards to run, for example every 3 hours or every Monday and Thursday</li>
</ul>
<p>The possibilities are endless! You can schedule backup scripts, system maintenance, email reports and so much more.</p>
<h2 id="heading-df-check-disk-space-usage">Df: Check Disk Space Usage</h2>
<p>Ever run out of disk space and wonder where it all went? The <code>df</code> command is here to help. df stands for “<em>disk free</em>” and shows you exactly how much space is used and available on your Linux system.</p>
<h3 id="heading-check-usage-for-all-mounted-filesystems">Check Usage for All Mounted Filesystems</h3>
<p>To see an overview of disk space usage for all mounted drives and partitions, simply run:</p>
<pre><code class="lang-bash">df -h
</code></pre>
<p>The <code>-h</code> flag formats the output in human-readable format, showing sizes in GB and MB instead of bytes. The output will show:</p>
<ul>
<li>Filesystem: The drive or partition name</li>
<li>Size: Total space</li>
<li>Used: Space currently in use</li>
<li>Available: Free space still available</li>
<li>Use%: Percentage of space used</li>
</ul>
<p>This gives you a quick snapshot of where you have space and where it's running low.</p>
<h3 id="heading-check-usage-for-a-specific-filesystem">Check Usage for a Specific Filesystem</h3>
<p>To check space on a specific drive or partition, pass its mount point to df:</p>
<p><code>df -h /home</code></p>
<p>This will show usage stats just for your /home partition.</p>
<p>Keeping an eye on disk usage with df and related tools is important for any Linux system administrator. No one wants to run out of space unexpectedly.</p>
<h2 id="heading-dmesg-view-kernel-messages">Dmesg: View Kernel Messages</h2>
<p>Ever wonder what’s happening behind the scenes in your Linux system? The <strong>dmesg</strong> command lets you peek under the hood and view messages from the kernel, the core of your operating system.</p>
<p>When your Linux system boots up, the kernel initializes hardware, loads drivers, starts services, and performs other startup tasks. The <strong>dmesg</strong> command displays the messages that get logged during this process so you can see what’s going on.</p>
<p>To view the kernel messages, just open your terminal and run the dmesg command. You'll see pages and pages of status <strong>updates</strong>, <strong>diagnostics</strong>, <strong>errors</strong>, and more as your system came to life. Skim through to check for any issues, or search for specific keywords like the name of your Wi-Fi adapter or other hardware components.</p>
<p>The <strong>dmesg</strong> output can also provide clues to solving any problems you're having. For example, if your network isn’t working, <strong>check dmesg for error messages related to your Ethernet or wireless card</strong>. You may spot something like “error initializing network device eth0” that points you to a driver issue.</p>
<p>The <code>dmesg</code> command is a handy diagnostic tool for any Linux system administrator or power user. It offers an inside look at your Linux system and can help uncover the source of both major malfunctions and minor annoyances. Ps: you can feel like a hacker.</p>
<h2 id="heading-grep-search-for-patterns-in-files">Grep: Search for Patterns in Files</h2>
<p>The grep command allows you to search for patterns in files and text. It’s ideal when you need to find something specific in a sea of data.</p>
<p>Say you have a massive log file full of information, but you only want to see the lines containing the word “error.” Just run:</p>
<pre><code class="lang-bash">grep error log.txt
</code></pre>
<p>This will print only the lines in log.txt that contain the word “error.”</p>
<p>You can also use grep to search for patterns rather than just words. For example, to find all lines in a file that start with “A” followed by a number, use:</p>
<pre><code class="lang-bash">grep ^A[0-9] log.txt
</code></pre>
<p>The <code>^A</code> anchors the match to the start of the line, and [0-9] matches any digit.</p>
<p>Grep has many more advanced features as well. You can use:</p>
<ul>
<li>Regex patterns for complex searches</li>
<li><code>-i</code> to ignore case</li>
<li><code>-v</code> to invert the search and show lines that <em>don’t</em> match</li>
<li><code>-c</code> to just get a count of matches</li>
<li><code>-r</code> to recursively search all files in a directory</li>
</ul>
<p>The next time you need to search through files, don’t do it manually—let grep do the work for you.</p>
<h2 id="heading-headtail-view-the-firstlast-part-of-a-file">Head/Tail: View the First/Last Part of a File</h2>
<p>Have you ever needed to quickly check just the first or last few lines of a long file? The head and tail commands are perfect for that.</p>
<p>The <code>head</code> command shows you the first 10 lines of a file by default. You can specify how many lines you want to see by using the <code>-n</code> flag, like <code>head -n 5 filename</code> to show the first 5 lines.</p>
<p>The <code>tail</code> command shows you the last 10 lines of a file by default. Again, use the <code>-n</code> flag to specify how many lines you want to see, like <code>tail -n 20 filename</code> to show the last 20 lines.</p>
<p>Both <code>head</code> and <code>tail</code> are useful when you want to do a quick check of the start or end of a long file without having to scroll through the entire thing. Some other uses of these commands:</p>
<ul>
<li>Checking log files for recent errors or warnings</li>
<li>Viewing email headers</li>
<li>Previewing configuration files</li>
<li>And more!</li>
</ul>
<p>Give <code>head</code> and <code>tail</code> a try – you'll be amazed at how much simpler they make tasks you do all the time.</p>
<h2 id="heading-ps-list-running-processes">Ps: List Running Processes</h2>
<p>The Ps command allows you to see info about the processes running on your system. This includes programs, commands, and daemons that are currently active. Using Ps is a quick way to get an overview of what your Linux system is doing at the moment and the system resources each process is using.</p>
<p>To see a basic list of running processes, enter:</p>
<pre><code class="lang-bash">ps aux
</code></pre>
<p>This will show you:</p>
<ul>
<li>A: All processes</li>
<li>U: User</li>
<li>X: Processes without terminals</li>
</ul>
<p>The output will contain info like:</p>
<ul>
<li><strong>USER</strong>: The owner of the process</li>
<li><strong>PID</strong>: The process ID</li>
<li><strong>%CPU</strong>: The CPU usage</li>
<li><strong>%MEM</strong>: The memory usage</li>
<li><strong>VSZ</strong>: The virtual memory usage</li>
<li><strong>TTY</strong>: The terminal associated with the process</li>
<li><strong>STAT</strong>: The process state (Running, Sleeping, Zombie, and so on.)</li>
<li><strong>START</strong>: The start time of the process</li>
<li><strong>TIME</strong>: The CPU time used</li>
<li><strong>COMMAND</strong>: The command that started the process</li>
</ul>
<p>You can also filter the Ps output by:</p>
<ul>
<li>Username: <code>ps aux | grep root</code></li>
<li>Process name: <code>ps aux | grep cron</code></li>
<li>PID: <code>ps aux | grep 555</code></li>
</ul>
<p>The Ps command allows you to quickly check in on what your system is doing and ensure there are no runaway or zombie processes hogging resources. For any Linux user, <code>Ps</code> is an indispensable tool for system monitoring and troubleshooting.</p>
<h2 id="heading-rsync-sync-files-and-folders">Rsync: Sync Files and Folders</h2>
<p>As a Linux user, you’ve probably found yourself needing to sync files and folders between locations. Maybe you have files on your desktop you need to transfer to your laptop, or you want to backup your most important folders to an external drive. The rsync command makes syncing and backing up your files a breeze.</p>
<p>Rsync is a fast and versatile file copying tool. It can copy and sync files and folders locally or remotely over SSH. It’s smart enough to only transfer the differences between two locations, saving time and bandwidth.</p>
<p>To use rsync, open your terminal and enter the command:</p>
<pre><code class="lang-bash">rsync [options] <span class="hljs-built_in">source</span> destination
</code></pre>
<ul>
<li>The source is the location of the files you want to copy. This could be a folder on your desktop or a remote server.</li>
<li>The destination is where you want to copy the files. This could be an external drive mounted on your system or a folder on another server.</li>
<li>Options allow you to specify items like:</li>
<li><code>-a</code>: Archive mode which preserves permissions, timestamps, group, owner and symlinks</li>
<li><code>-v</code>: Verbose output so you can see what’s being copied</li>
<li><code>-z</code>: Compression to speed up transfers over slow networks</li>
<li>-h: Human-readable sizes (e.g. 1K, 234M, 2G)</li>
</ul>
<p>Rsync is a must-have tool for any Linux user. Once you get the hang of it, you’ll be syncing and backing up your files with confidence. </p>
<p>For broad reading please refer to <a target="_blank" href="https://www.freecodecamp.org/news/rsync-examples-rsync-options-and-how-to-copy-files-over-ssh/">RSync Examples – Rsync Options and How to Copy Files Over SSH</a>.</p>
<h2 id="heading-the-powerful-pipe-viewer-pv">The Powerful Pipe Viewer (pv)</h2>
<p>Ever wanted to see the progress of data through a pipe? The <code>pv</code> command allows you to do just that. It's a pipe viewer that shows you the progress of data through a pipeline.</p>
<p>Say you have a large file that you want to compress, like a video or backup file. Rather than staring at a blinking cursor while gzip does its thing, you can see the progress with pv. Just pipe the data through pv, then to gzip:</p>
<pre><code class="lang-bash">cat mylargefile.mp4 | pv | gzip &gt; mylargefile.mp4.gz
</code></pre>
<p><code>pv</code> will display the throughput and estimated time remaining as your data is compressed. It's a simple way to get feedback on long-running commands.</p>
<p>You can also use <code>pv</code> to see <a target="_blank" href="https://www.techtarget.com/searchnetworking/definition/throughput#:~:text=Throughput%20is%20a%20measure%20of,and%20network%20systems%20to%20organizations.">throughput</a> and transfer rates of data over the network. For example, when copying a file with <code>scp</code> or <code>rsync</code>, add <code>pv</code> to the pipeline:</p>
<pre><code class="lang-bash">rsync -avz myfiles user@host:/backup | pv
</code></pre>
<p>Now you'll see the progress of your files copying over the network. pv gives you information like:</p>
<ul>
<li>Transferred bytes</li>
<li>Transfer rate</li>
<li>ETA</li>
<li>Progress</li>
<li>And more</li>
</ul>
<p>It's a handy tool to give you more insight into what's happening in those long-running terminal commands.</p>
<h2 id="heading-mtr-network-diagnostics">mtr: Network Diagnostics</h2>
<p>Have you ever needed to diagnose network issues but didn’t have access to expensive tools? mtr is a simple but powerful Linux network diagnostic tool. It combines the functionality of the ‘traceroute’ and ‘ping’ programs in a single network diagnostic tool.</p>
<p><code>mtr</code> sends <a target="_blank" href="https://www.freecodecamp.org/news/traceroute-and-ping/">ICMP</a> echo requests to test the network connectivity between the host <code>mtr</code> runs on and a user-specified destination host. It prints the response times and packet loss statistics for each router along the path. This allows you to quickly pinpoint network issues.</p>
<p>To use mtr, open a terminal and enter:</p>
<pre><code class="lang-bash">mtr [domain name or IP address]
</code></pre>
<p>For example, to trace the route to google.com, enter:</p>
<pre><code class="lang-bash">mtr google.com
</code></pre>
<p>mtr will start tracing the route and printing results that update in real time. It will show:</p>
<ul>
<li>The IP address and hostname of each router along the path</li>
<li>The percentage of packet loss for each router</li>
<li>The response times in milliseconds for each router</li>
</ul>
<p>The output will continue to update until you press Ctrl+C to stop the trace.</p>
<p>mtr is a simple but useful tool for any Linux network administrator. It can save you hours of troubleshooting time when the network goes down by helping you identify the source of latency or packet loss.</p>
<h2 id="heading-jq-parse-json">jq: Parse JSON</h2>
<p>Ever come across a messy JSON file and wish you had an easy way to parse through it? Meet jq, a command line tool that lets you filter and analyze JSON data with ease.</p>
<p>jq works like a filter. You pass it JSON data on stdin, and it passes the filtered/transformed data to stdout. </p>
<p>For example, say you have a JSON file called <code>data.json</code> with an array of objects. You can filter it to only show objects where <code>name</code> is equal to <code>John</code> like this:</p>
<pre><code class="lang-bash">cat data.json | jq <span class="hljs-string">'.[] | select(.name == "John")'</span>
</code></pre>
<p>This will print only the John objects to the console.</p>
<p>jq supports many more filters than just <code>select()</code>, here are a few more useful ones:</p>
<ul>
<li><code>.key</code>: Access a key from objects</li>
<li><code>.[10:]</code>: Show elements from index 10 onwards</li>
<li><code>.[10:15]</code>: Show elements from index 10 to 15</li>
<li><code>length</code>: Print the length of an array</li>
<li><code>map(.)</code>: Apply a filter to each element of an array</li>
<li><code>group_by(.key)</code>: Group objects by a key</li>
</ul>
<p>With jq, you can manipulate JSON data in pretty much any way you want right from the command line. <code>jq</code> may seem niche, but JSON is used everywhere on the web, so being able to analyze and transform it efficiently is a useful skill.</p>
<h2 id="heading-tac-view-config-files-in-reverse">tac: View Config Files in Reverse</h2>
<p>Have you ever made a mistake while editing a config file and saved the changes, only to realize you preferred the previous version? The <code>tac</code> command allows you to quickly view config files in reverse, so you can see what the file looked like before your edits.</p>
<p>Tac simply prints files in reverse order, line by line. To view a file called <code>config.txt</code> in reverse, run:</p>
<pre><code class="lang-bash">tac config.txt
</code></pre>
<p>This will print the last line of the file first, then the second last line, and so on until it reaches the first line.</p>
<ul>
<li>Use tac when you want to <strong>quickly view a log file in reverse</strong> to see the latest entries first.</li>
<li>Tac can also be useful when <strong>editing config files through the command line</strong>. If you make a mistake, run tac to see what the file looked like before so you can revert your changes.</li>
</ul>
<p>Tac is a simple but useful utility to have in your Linux toolkit.</p>
<h2 id="heading-perf-analyze-cpu-performance">perf: Analyze CPU Performance</h2>
<p>If you've ever wondered why your Linux system seems slower over time, the perf command can help you figure it out. Perf is a profiling tool in Linux that can analyze the performance of your CPU to help identify any bottlenecks.</p>
<p>To get started, run the basic <code>perf list</code> command to see a list of the events you can monitor. There are hundreds! Some of the most useful ones for profiling CPU performance are:</p>
<ul>
<li><code>cpu-clock</code>: Measure the CPU clock cycles</li>
<li><code>task-clock</code>: Measure the time spent on task execution</li>
<li><code>cache-misses</code>: Count the number of cache misses</li>
<li><code>branch-misses</code>: Count the number of branch prediction misses</li>
</ul>
<p>Pick an event you want to monitor, then run a command like:</p>
<pre><code class="lang-bash">perf <span class="hljs-built_in">stat</span> -e cpu-clock sleep 5
</code></pre>
<p>This will run the <code>sleep 5</code> command and measure the <code>cpu-clock</code> event while it's running. Perf will then give you a summary of the stats for that event.</p>
<p>To get more detailed profiling info, use the <code>perf record</code> command. For example, to profile a script called <code>script.sh</code>, run:</p>
<pre><code class="lang-bash">perf record script.sh
</code></pre>
<p>This will run the script and record the profiling data. You can then view the results with:</p>
<pre><code class="lang-bash">perf report
</code></pre>
<p>This gives you an interactive report to analyze the results. You'll see things like:</p>
<ul>
<li>The percentage of time spent in each function</li>
<li>The actual time spent in each function</li>
<li>The number of calls to each function</li>
</ul>
<p>Using perf, you have a powerful tool to optimize the performance of your Linux system. Perf really is an amazing (if underused) tool.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it, some helpful Linux commands that will make you feel like a power user in no time. </p>
<p>With these tricks up your sleeve, you'll be zipping around Linux like a pro. The next time you're stuck or frustrated, give one of these a shot. You might just surprise yourself with what you can accomplish.</p>
<p>Linux is an incredibly powerful operating system if you know how to speak its language. Consider this your starter guide to becoming fluent.</p>
<p>I am <a target="_blank" href="https://rahul.biz/">Rahul</a>, 19, Hustler. I am building <a target="_blank" href="https://fueler.io/register?referral_token=94329340-3e14-4e1e-83fa-bd5e1992">Fueler.io</a> a platform for generalists to create proof of work profile and land opportunities. Let’s connect on <a target="_blank" href="https://twitter.com/rahul_wip">Twitter</a>.  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Promise.allSettled() in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever worked with promises in JavaScript and gotten frustrated when one rejects and ruins everything?  You write some promise-based code, everything is chugging along nicely, and then boom – one little promise rejects and the whole chain come... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-promise-allsettled-in-javascript/</link>
                <guid isPermaLink="false">66c861a251f56da58aee7b7a</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jun 2023 17:03:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/andrew-petrov-hopnkQoC0dg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever worked with promises in JavaScript and gotten frustrated when one rejects and ruins everything? </p>
<p>You write some promise-based code, everything is chugging along nicely, and then boom – one little promise rejects and the whole chain comes crashing down.</p>
<p>Your code grinds to a halt and you're left wondering why JavaScript couldn't just ignore that one little hiccup and continue on its merry way. Well, friend, do I have good news for you.</p>
<p>Meet <code>Promise.allSettled()</code>, your new best friend and the promise you never knew you needed. <code>Promise.allSettled()</code> is a game-changer, allowing you to wait for all your promises to settle – either resolve or reject – and then take action based on the results.</p>
<p>No more ruined promise chains or unhandled rejections. Just pure, unadulterated promise bliss. Join me as we dive into this little-known but incredibly useful promise method and see just how much it can simplify your <a target="_blank" href="https://www.freecodecamp.org/news/asynchronous-javascript/">asynchronous JavaScript</a> code.</p>
<h2 id="heading-what-is-promiseallsettled">What Is Promise.allSettled()?</h2>
<p>So you want to use JavaScript's Promise.allSettled() method, but aren't quite sure how it works or why you'd want to use it? No worries, I've got you covered.</p>
<p><code>Promise.allSettled()</code> waits for all promises you give it to settle, meaning either resolve or reject. It then returns an array of objects with the status and value or reason for each promise. </p>
<p>This is useful when you have multiple asynchronous tasks that you want to ensure have completed, but don't necessarily care if some fail.</p>
<p>For example, say you have three API calls that return promises, and you want to get all the data back from the successful calls, even if one fails. You could do:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([apiCall1(), apiCall2(), apiCall3()]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {});
</code></pre>
<p>This will run all three API calls, and the <code>.then()</code> callback will be called once they have all settled. The results array will have three objects: one for each promise, with either a status of 'fulfilled' and the data, or 'rejected' and the error. </p>
<p>We can filter to just get the successful calls, and proceed using that data.</p>
<p>The key things to remember are:</p>
<ul>
<li><code>Promise.allSettled()</code> waits for all input promises to settle and returns their outcomes.</li>
<li>Settled means either resolved (fulfilled) or rejected.</li>
<li>It returns an array of objects with status and value/reason for each input promise.</li>
<li>It allows handling successful promises even when some reject.</li>
</ul>
<h2 id="heading-the-problem-with-promiseall-and-the-solution-with-promiseallsettled">The problem with <code>Promise.all()</code> and the solution with <code>Promise.allSettled()</code></h2>
<p><code>Promise.all()</code> is great when you want to wait for multiple promises to complete and get an array of all the resolved values. But it has one major downside: if any of the promises reject, the entire <code>Promise.all()</code> rejects immediately.</p>
<p>This can be problematic in some cases. For example, say you make requests to three different backend services, and you don't really care if one fails as long as the other two succeed. With <code>Promise.all()</code>, a single rejected promise would reject the entire group, and you'd miss the successful responses from the other promises.</p>
<p>Fortunately, there's a simple solution: <code>Promise.allSettled()</code>. This works similarly to <code>Promise.all()</code> but instead of rejecting immediately if any promise rejects, it waits for all promises to settle (either resolve or reject) and then returns an array of objects with the status and value/reason for each promise.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>),
  <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"2"</span>)),
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">3</span>),
]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
  <span class="hljs-comment">// results is an array of:</span>
  <span class="hljs-comment">// {status: "fulfilled", value: 1}</span>
  <span class="hljs-comment">// {status: "rejected", reason: Error}</span>
  <span class="hljs-comment">// {status: "fulfilled", value: 3}</span>
});
</code></pre>
<p>As you can see, even though the second promise rejected, we still get the resolved values from the other promises. This allows you to handle rejections gracefully without missing any successful responses.</p>
<p><code>Promise.allSettled()</code> provides more flexibility in these types of situations. You get the full picture of all your promises, regardless of some rejecting, so you have the opportunity to still make use of any resolved values and handle rejections appropriately.</p>
<p>So next time you need to wait on multiple promises but can't afford to miss any resolved values due to a rejection, be sure to reach for <code>Promise.allSettled()</code>! It's a very useful addition to the <a target="_blank" href="https://www.freecodecamp.org/news/tag/promises/">Promise API</a>.</p>
<h2 id="heading-common-questions-about-promiseallsettled">Common Questions About <code>Promise.allSettled()</code></h2>
<h3 id="heading-will-promiseallsettled-slow-down-my-code">Will <code>Promise.allSettled()</code> slow down my code?</h3>
<p>Not really. <code>Promise.allSettled()</code> simply waits for all the promises you pass to it to settle, either by fulfilling or rejecting. It doesn’t do anything else that would impact performance.</p>
<h3 id="heading-can-i-still-catch-errors-with-promiseallsettled">Can I still catch errors with <code>Promise.allSettled()</code>?</h3>
<p>Yes, you absolutely can! <code>Promise.allSettled()</code> will give you the outcome of each promise, whether it was fulfilled or rejected. </p>
<p>For any rejected promises, you'll get the reason why it rejected, usually an error. You can catch these errors in the <code>.catch()</code> handler of the <code>Promise.allSettled()</code> call.</p>
<h3 id="heading-when-should-i-use-promiseallsettled-vs-promiseall">When should I use <code>Promise.allSettled()</code> vs <code>Promise.all()</code>?</h3>
<p>Use <code>Promise.allSettled()</code> when you want to run multiple promises in parallel, but don’t want a single rejected promise to cause the entire group to reject. </p>
<p>For example, if you're fetching data from multiple third-party APIs, a rejected promise from one API shouldn’t stop you from getting data from the other APIs.</p>
<p>Use <code>Promise.all()</code> when you want to run promises in parallel but need them all to successfully complete for your code to continue. </p>
<p>For example, if you need to fetch data from two APIs to display on a page, you’d want both promises to fulfill before rendering the data.</p>
<h3 id="heading-can-i-get-the-results-of-the-settled-promises">Can I get the results of the settled promises?</h3>
<p>Yes! <code>Promise.allSettled()</code> returns an array of objects with the status and value/reason for each promise. For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>),
  <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"2"</span>)),
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">3</span>),
]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(results);
  <span class="hljs-comment">/*
    [
      { status: "fulfilled", value: 1 },
      { status: "rejected", reason: Error: 2 },
      { status: "fulfilled", value: 3 }
    ]
    */</span>
});
</code></pre>
<p>You'll get information on all the promises, whether they fulfilled or rejected, so you have the full picture of the parallel operations.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it. <code>Promise.allSettled()</code> is a handy method you never knew you needed. </p>
<p>No longer do you have to wrap <code>Promise.all()</code> in a try/catch just to handle potential rejections. You can let <code>Promise.allSettled()</code> handle all that for you and just focus on the resolved values. Your async code will be cleaner and easier to read.</p>
<p>Thank you for reading. I am <a target="_blank" href="https://rahul.biz">Rahul</a>, 19, and a technical writer. Here is my <a target="_blank" href="https://fueler.io/rahoool">proof of work</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use APIs in Your Projects to Practice Your Coding Skills ]]>
                </title>
                <description>
                    <![CDATA[ As web developers, we all know that practice makes perfect. But when it comes to practice, it's easy to get stuck in a programming rut. But how do you come up with new ideas to build? Sooner or later, you will find yourself running out of features to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-apis-to-practice-coding-skills/</link>
                <guid isPermaLink="false">66c861a8f8acdfb6b71e61be</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ projects ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Thu, 20 Apr 2023 22:28:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-build-projects.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As web developers, we all know that practice makes perfect. But when it comes to practice, it's easy to get stuck in a programming rut.</p>
<p>But how do you come up with new ideas to build? Sooner or later, you will find yourself running out of features to add or algorithms to implement.</p>
<p>Fortunately, there is a simple solution: APIs. <a target="_blank" href="https://www.freecodecamp.org/news/how-apis-work/">APIs</a> are infinitely versatile and you can use them to create countless unique projects.</p>
<p>To help jumpstart your coding practice, I'll show you 9 different project ideas—all of which leverage APIs in some way—that you can use to build up your programming skills.</p>
<p>Let's get started!</p>
<h2 id="heading-how-to-build-an-e-signature-app"><strong>How to Build an E-Signature App</strong></h2>
<p>We'll start by building an e-signature app using a few APIs. These APIs have most of the features required to build an e-signature app.</p>
<p>You can use the <a target="_blank" href="https://developers.docusign.com/docs/esign-rest-api/reference/">DocuSign API</a> to generate personalized digital signatures, set up workflows, templates, tagging rules, secure document storage, encryption, and so on in a safe environment.</p>
<p>So how would you get started with this project? I'd recommend using React, Node and MongoDB to create this type of app. Here's a rough outline of some steps you could take:</p>
<ul>
<li>Read the DocuSign API documentation and signup for a developer account. </li>
<li>Design the UI using React or Angular</li>
<li>Implement the back-end logic using NodeJS</li>
<li>Test and debug your app in the DocuSign API sandbox, and you're good to go.</li>
</ul>
<h2 id="heading-how-to-build-a-stock-market-tracking-app"><strong>How to Build a Stock Market Tracking App</strong></h2>
<p>If you're looking to sharpen your development abilities while also producing something worthwhile and impressive, creating a stock market tracking application could be a great option.</p>
<p>This type of app can monitor stock values and store them in a database for fast access and evaluation. Utilizing the <a target="_blank" href="https://www.alphavantage.co/documentation/">Alpha Vantage API</a>, you can access data on stocks and prices.</p>
<p>For this project, you'll need to use a charting library like Chart.js, Highcharts or D3.js. These libraries will help to show the data in more visually appealing way. </p>
<p>You may also want to store data such as stock quotes, historical data, and user portfolios, so you'll need a database for that. I'd suggest MongoDB or PostgreSQL as a couple good choices. For the front end, React would be a good choice, and you can use Node for the back end. </p>
<p>So how do you get started? </p>
<ol>
<li>First, you'll want to identify the key functionalities you want to include, like real-time stock quotes, historical stock data, portfolio tracking, customizable watchlists, alerts, and so on.</li>
<li>You'll use the Alpha Vantage API as your data source for stock market data. Alpha Vantage provides a comprehensive and reliable set of APIs for accessing stock market data, including stock quotes, technical indicators, historical data, and more.</li>
<li>You'll also need to create an intuitive and user-friendly interface.</li>
<li>You'll have to integrate the Alpha Vantage API to fetch real-time or historical stock market data. </li>
<li>Then you'll implement the core functionality using the Alpha Vantage API. This can include displaying real-time stock quotes, charts, news, portfolio tracking, watchlists, alerts, and notifications.</li>
<li>Finally, you'll make sure user data and financial information is protected and secure by implementing appropriate security measures, such as data encryption, authentication, and authorization.</li>
</ol>
<p>Building an application like this is an excellent way to help you practice your development skills with something exciting and useful. </p>
<h2 id="heading-how-to-build-a-delivery-management-app"><strong>How to Build a Delivery Management App</strong></h2>
<p>Creating a delivery management app is actually quite straightforward. It helps entrepreneurs and business owners get their goods delivered to customers in an efficient manner.</p>
<ul>
<li>You'll need tools like <a target="_blank" href="https://developers.google.com/maps">Google Maps</a>, <a target="_blank" href="https://developers.google.com/maps/documentation/geocoding/overview">Geocoding</a>, or other geolocation APIs to get started.</li>
<li>You'll have to create an interface for customers to enter their delivery address and track the real-time location of delivery drivers using the Google Maps API.</li>
<li>For each driver, you should create a profile with contact information, estimated time of arrival, and any details about the goods being delivered.</li>
<li>Customers should be able to track their deliveries in real-time while calculating distance and route optimization for better predictions on arrival times.</li>
</ul>
<p>It's just like creating a smaller version of Zomato or DoorDash (in the US).</p>
<h2 id="heading-how-to-develop-an-online-shopping-mall-app"><strong>How to Develop an Online Shopping Mall App</strong></h2>
<p>If you're ready to work with a lot of different APIs, this online shopping mall app project will be a fun one for you. You'll use the below APIs to build a modern e-commerce app for selling anything from clothes and accessories to groceries or furniture.</p>
<p>For this project, you will need to use the following APIs:</p>
<ul>
<li>A payment gateway API like the PayPal API or the Stripe API to collect payment from users.</li>
<li>A query language like GraphQL API to manage data operations and fetch the data needed by the app.</li>
<li>A shipping API to provide delivery services to customers.</li>
<li>An inventory API to sync inventory across multiple stores and warehouses.</li>
<li>A review API to record customer reviews of the products.</li>
</ul>
<p>By using these APIs and developing your own front-end code, you can create an online shopping mall application that will make it easier for customers to order products from multiple stores.</p>
<h2 id="heading-how-to-design-a-tax-rate-calculator-tool"><strong>How to Design a Tax Rate Calculator Tool</strong></h2>
<p>For your next project, why not try designing a tax rate calculator tool for personal use?</p>
<p>With taxes varying from country to country and state to state, it can be confusing to accurately calculate your tax rate.</p>
<p>You'll need an API, like <a target="_blank" href="https://developers.taxjar.com/api/reference/">TaxJar's SalesTax API</a>, that provides up-to-date information about local sales taxes for products and services.</p>
<p>With basic HTML, CSS, JavaScript and API knowledge, you can create a fully functional tax rate calculator tool. Not only will this be helpful to users, but it also offers great practice development experience for developers.</p>
<h2 id="heading-how-to-develop-an-image-editing-app"><strong>How to Develop an Image Editing App</strong></h2>
<p>Developing an image editing web application can be quite a bit of work, but there are many APIs that can help you simplify some of the processes like adjusting contrast, resizing an image, or making some quick image edits.</p>
<p>If you're thinking of developing your own image editor, here are some resources:</p>
<ul>
<li>You can use <a target="_blank" href="https://imagemagick.org/index.php">ImageMagick's Image Processing API</a> to manipulate and transform images.</li>
<li>You can use <a target="_blank" href="https://azure.microsoft.com/en-in/products/cognitive-services/computer-vision">Azure Computer Vision's APIs</a> to add text overlays on images.</li>
<li>You can use Slazzer's <a target="_blank" href="https://www.slazzer.com/api">Remove Background</a> API to clear up any unwanted background noise or add this feature if necessary.</li>
<li><a target="_blank" href="https://labs.everypixel.com/api">Everypixel Image Collage API</a> helps you create customized photo collages.</li>
</ul>
<h2 id="heading-how-to-create-an-online-video-conferencing-app"><strong>How to Create an Online Video Conferencing App</strong></h2>
<p>Video conferencing apps are becoming more and more popular as they provide us with an easy way to stay connected, no matter the distance.</p>
<p>It's possible to build your own video conferencing app with the help of  APIs, and a bit of coding know-how.</p>
<p>To begin with, you'll need an API that provides the video conferencing feature, such as the <a target="_blank" href="https://www.twilio.com/docs/video">Twilio Video API</a>. </p>
<p>You'll also need an API for authentication such as the <a target="_blank" href="https://auth0.com/docs/api">Auth0 API</a>.</p>
<p>With these two APIs combined, you can make an app that allows users to securely register and log in, and then start a video call with their contacts.</p>
<h2 id="heading-how-to-build-a-real-estate-management-system"><strong>How to Build a Real Estate Management System</strong></h2>
<p>Building a real estate management system to keep track of your properties sounds like a great project idea, don't you agree?</p>
<p>By combining different APIs, you can assemble a system that would help you efficiently manage and maintain your investments.</p>
<p>You can use the <a target="_blank" href="https://developers.google.com/maps">Google Maps API</a>  to acquire geographical info regarding your properties and store it in the database.</p>
<p>Also, with the assistance of APIs such as the Zillow API or the Trulia API, you can get accurate pricing info for similar properties located in particular areas.</p>
<p>This is beneficial when it comes to getting the market value of your properties.</p>
<p>Lastly, the <a target="_blank" href="https://developers.google.com/calendar/api/guides/overview">Google Calendar API</a> or the Microsoft Outlook API can be utilized to generate automated notifications when collecting rent payments from tenants.</p>
<p>In summary, merging these APIs can help you create an effective real estate management system that saves time and money while properly organizing your properties!</p>
<h2 id="heading-how-to-build-an-event-planning-organizer-tool"><strong>How to Build an Event Planning Organizer Tool</strong></h2>
<p>Organizers looking to plan events of all sizes – from birthdays to weddings, and corporate gatherings – need help managing the tasks associated with them.</p>
<p>An event planning app provides a great tool for this, giving users deadlines and reminders as they work to prepare for the occasion.</p>
<ul>
<li>Using Google Calendar and the <a target="_blank" href="https://developer.atlassian.com/cloud/trello/rest/">Trello API</a>, it's possible to provide calendar integration features that pull in event details and allow users to sync between multiple platforms.</li>
<li>The Trello API also helps users keep track of tasks both before and after an event, creating lists that outline what needs to be accomplished.</li>
<li>Each task can be assigned a due date and a priority level, so that you can be sure nothing is missed or overlooked before the big day arrives.</li>
</ul>
<p>You can also set up a notification feature for users, letting them know when a task needs attention or providing them with helpful reminders regarding upcoming deadlines.</p>
<p>All of these features combined would make your tool a useful resource for any type of event planner or organizer.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>You can develop your skills and knowledge as a programmer by building some basic projects. With the help of the APIs and project ideas presented in this article, you can build some interesting projects and enhance your development journey.</p>
<p>APIs can be intimidating at first, but with constant practice, you'll get used to working with them. And as your programming skills grow, you’ll be able to push the boundaries and explore more possibilities.</p>
<p>Happy coding!</p>
<p>Read more on APIs:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/public-apis-for-developers/">Public APIs for Developers</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/rules-of-api-testing-for-beginners/">API Testing Best Practices – How to Test APIs for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/use-react-and-apis-to-build-a-weather-app/">Use React and APIs to Build a Weather App</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Protect Your PWA – Web App Security Best Practices ]]>
                </title>
                <description>
                    <![CDATA[ Hey, everybody! I'm Rahul. In today's world, web apps have become more prevalent because they work seamlessly on multiple devices. But as with any application, PWAs can be vulnerable to security threats, which can compromise user data and damage the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-protect-your-pwa/</link>
                <guid isPermaLink="false">66c861a051f56da58aee7b78</guid>
                
                    <category>
                        <![CDATA[ progressive web app ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PWA ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Mon, 17 Apr 2023 21:28:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/pwa.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hey, everybody! I'm <a target="_blank" href="https://fueler.io/rahoool">Rahul</a>. In today's world, web apps have become more prevalent because they work seamlessly on multiple devices. But as with any application, PWAs can be vulnerable to security threats, which can compromise user data and damage the reputation.</p>
<p>It's natural to get excited about launching something new, but it's also important to remember the basics of website security. As a developer, you know it’s important to protect your web app from malicious users, attackers, hackers, and other cyber threats.</p>
<p>You've put in a lot of hard work building the perfect user experience and now it's time to keep it secure.</p>
<p>In this tutorial, we'll walk through some simple yet powerful strategies that help you protect your PWA. Let’s get started!</p>
<h1 id="heading-what-is-a-pwa">What is a PWA?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/undraw_progressive_app_m-9-ms.svg" alt="PWA Illustration by undraw.co" width="600" height="400" loading="lazy">
<em>PWA Illustration by undraw.co</em></p>
<p>Are you interested in bringing a native mobile app experience to your users without the headache of app development? Progressive Web App is the way.</p>
<p>PWAs are a type of web application that uses the latest web tech to deliver a user experience similar to that of a native mobile app.</p>
<p>They are built to take advantage of native mobile device features and work for apps regardless of whether the user has poor or no internet connection.</p>
<p>Additionally, PWAs are reliable, fast, and engaging — plus, they’re easier to develop and maintain than traditional apps.</p>
<p>The best part about PWAs is that they offer the same experience on all major browsers like Chrome, Firefox, Edge and Safari — so you don’t have to be concerned about compatibility issues.</p>
<p>Also, since PWAs don’t require installation from an app store, users don’t have to wait for their device manufacturer to approve or update them.</p>
<p>All these factors make PWAs ideal for businesses looking for cost-effective mobile solutions.</p>
<h1 id="heading-how-to-secure-a-pwa">How to Secure a PWA</h1>
<h2 id="heading-authentication-and-authorization-in-pwas">Authentication and Authorization in PWAs</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/undraw_authentication_re_svpt.svg" alt="Image" width="600" height="400" loading="lazy">
<em>authentication illustration by undraw.co</em></p>
<p>If you're building a Progressive Web App (PWA), you need to ensure that it is properly secured. In order to do this, you'll need to understand the basics of authentication and authorization.</p>
<p>Authentication is the process by which users prove their identity and verify that they have the proper authorization to access the app.</p>
<p>Authorization, on the other hand, ensures that those users have access only to areas and content that they are allowed to see, while enforcing restrictions on what they can do.</p>
<p>In order to implement effective authentication and authorization within your PWA, there are some best practices you should follow.</p>
<ol>
<li>Firstly, use secure passwords that are difficult for hackers or bots to guess or crack, as well as two-factor authentication (2FA) for added security.</li>
<li>Secondly, use roles-based access control (RBAC) for authorization. This establishes user permissions based on roles which can be quickly adjusted when needed.</li>
<li>Lastly, use HTTPS with SSL/TLS encryption for all web traffic from your PWA. This will ensure that all data sent between clients and servers is encrypted, protecting user information from malicious actors.</li>
</ol>
<p>It is important to keep in mind that authentication and authorization can also be vulnerable to attack by malicious users if not implemented correctly. So it is essential to stay aware of common attack vectors like SQL injection threats and cross-site scripting (XSS) attacks.</p>
<p>By implementing proper security measures such as input validation and penetration testing, you can protect your PWA from these threats.</p>
<h2 id="heading-how-to-use-https-and-ssltls-to-secure-your-pwas">How to Use HTTPS and SSL/TLS to Secure Your PWAs</h2>
<p>HTTPs and SSL/TLS are two of the most important tools when it comes to securing PWAs.</p>
<p>Let's see what exactly they are:</p>
<h3 id="heading-what-is-https">What is HTTPS?</h3>
<p>HTTPS stands for Hyper Text Transfer Protocol Secure. It's a protocol used for secure communication between a web server and a web browser, and is vital for protecting data from being intercepted by third parties.</p>
<p>To put it simply, HTTPS helps ensure that the data you send and receive from your PWA is always secure.</p>
<h3 id="heading-what-is-ssltls">What is SSL/TLS?</h3>
<p>SSL (Secure Sockets Layer) and <a target="_blank" href="https://www.freecodecamp.org/news/what-is-tls-transport-layer-security-encryption-explained-in-plain-english/">TLS (Transport Layer Security)</a> are cryptographic protocols that provide authentication, encryption and data integrity.</p>
<p>These protocols allow secure connections between web browsers, applications, and servers over the internet via an encrypted handshake process.</p>
<p>As such, they play an important role in ensuring that your web app's data remains safe and secure.</p>
<h3 id="heading-best-practices-for-implementing-https-and-ssltls-in-pwas">Best Practices for Implementing HTTPS and SSL/TLS in PWAs</h3>
<p>To protect your PWA effectively, you should make sure that you're following some best practices for implementing HTTPS and SSL/TLS in PWAs:</p>
<ol>
<li>Use HTTPS Everywhere: Make sure that all of your pages are served over HTTPS, rather than insecure HTTP connections. This will help ensure your users' data is protected while they're on your website or application.</li>
<li>Install an SSL Certificate: This will enable HTTPs connections on your site and provide authentication between the server hosting your PWA and the users visiting it.</li>
<li>Regularly Test Connections: Ensure that all of your connections are still secure by testing them regularly for any vulnerabilities or risks to security</li>
<li>Implement Certificate Pinning: Certificate pinning is an important security measure that involves binding a host domain to a specific SSL certificate. This prevents <strong>man-in-the-middle attacks</strong> and will help protect your PWA from malicious actors.</li>
<li>Keep Your Security Protocols Up to Date: Regularly update your web server's security protocols to ensure that you're always running the most secure version.</li>
<li>Configure Appropriate Firewall Rules: Configure your firewall rules to allow only secure connections and block any suspicious traffic. This will help protect your PWA from malicious attacks.</li>
</ol>
<p>Once you've implemented these best practices, you can feel pretty confident that your PWA is as secure as possible.</p>
<p>But, <a target="_blank" href="https://www.freecodecamp.org/news/attacks-on-ssl-tls-and-how-to-protect-your-system/">security isn't just about preventing malicious attacks</a>. It's about ensuring that your users' data is always kept safe and secure.</p>
<p>By taking the above steps, you can ensure that your PWA is always compliant with the latest security standards and guidelines. This will help protect your users' data from unauthorized access and potential security threats.</p>
<h2 id="heading-how-to-protect-against-cross-site-scripting-xss-and-cross-site-request-forgery-csrf">How to Protect against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)</h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-protect-against-dom-xss-attacks/">Cross-site scripting</a> and <a target="_blank" href="https://www.freecodecamp.org/news/what-is-cross-site-request-forgery/">cross-site request forgery</a> are both security threats that can cause serious damage to PWAs.</p>
<p>XSS works by injecting malicious code into the browser via a vulnerable web application.</p>
<p>This code can be used to exfiltrate data from the PWA, like passwords or credit card numbers, or to execute any other malicious code.</p>
<p>CSRF, on the other hand, is a form of attack that manipulates a user's browser into sending forged requests without them knowing.</p>
<p>This can be used to execute actions within an application, such as transferring money or deleting data.</p>
<p>Fortunately, there are steps you can take to protect your PWA against XSS and CSRF attacks:</p>
<ul>
<li><strong>Sanitize all user input</strong>: Sanitizing user input is one of the best ways to protect against XSS and CSRF attacks. Make sure that you always validate and filter out any potentially harmful content before it’s added to your database.</li>
<li><strong>Use CAPTCHA protection</strong>: Adding CAPTCHA protection to web forms will help ensure that any requests from users are coming from real people rather than malicious bots or scripts.</li>
<li><strong>Use secure cookies</strong>: Secure cookies allow you to store data about your users in an encrypted format and limit access only to authorized users. This can help make sure that data isn’t exposed in case of a compromise.</li>
</ul>
<p>By taking these steps, you can help protect your PWA against XSS and CSRF attacks.</p>
<h2 id="heading-how-to-develop-a-content-security-policy-csp">How to Develop a Content Security Policy (CSP)</h2>
<p>Content Security Policy (CSP) is an important web security mechanism designed to prevent malicious attacks.</p>
<p>To put it simply, a CSP is a set of rules that specify what sources are allowed when loading resources such as scripts, images, and stylesheets. By defining the sources of these content types, CSP helps protect your applications from cross-site scripting (XSS) and data injection attacks.</p>
<p>By implementing a CSP on your PWA, you can add an extra layer of protection against malicious attacks.</p>
<p>Some best practices for implementing CSP include:</p>
<ul>
<li><strong>Defining allowed origins</strong>: This makes sure that only authorized sources can access content on your application.</li>
<li><strong>Whitelisting inline styles</strong>: When possible, use the nonce attribute to whitelist specific inline scripts and styles so that the code is only executed if the nonce matches what is specified in the policy.</li>
<li><strong>Disallowing unsafe methods</strong>: Include a directive that blocks dangerous methods such as eval() in order to protect against code injection attacks.</li>
<li><strong>Setting up reporting/logging</strong>: Configure reporting/logging so you can track incoming requests and flag any suspicious activity.</li>
</ul>
<p>By following these best practices and setting up CSP properly, you can effectively protect your PWAs from malicious attacks while ensuring they remain secure and performant.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In short, if you want to keep your web app secure, it’s important to follow best practice security protocols such as robust authentication and encryption, regular security patch updates, and secure APIs. It's also essential to have a secure development process in place to ensure that only the most secure code is being deployed.</p>
<p>Finally, user education is key when it comes to web apps. Providing users with a secure platform is only half the battle, as ultimately it’s up to the user to stay vigilant about their online security.</p>
<p>Read more on PWAs:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-are-progressive-web-apps/">What is a PWA? Progressive Web Apps for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/build-a-pwa-from-scratch-with-html-css-and-javascript/">How to build a PWA from scratch with HTML, CSS, and JavaScript</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
