<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Larry's Coding Corner]]></title><description><![CDATA[I'm Larry, an experienced developer specializing in Node.js and Golang, with additional frontend skills in React.js. For consulting or a chat, feel free to reac]]></description><link>https://larrylu.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 03:34:47 GMT</lastBuildDate><atom:link href="https://larrylu.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why 0.1 + 0.2 ≠ 0.3: A Deep Dive into IEEE 754 and Floating-Point Arithmetic]]></title><description><![CDATA[Discover floating-point errors and IEEE 754. Learn how computers handle numbers, common errors, and solutions to enhance your coding skills.]]></description><link>https://larrylu.dev/why-01-02-03-a-deep-dive-into-ieee-754-and-floating-point-arithmetic</link><guid isPermaLink="true">https://larrylu.dev/why-01-02-03-a-deep-dive-into-ieee-754-and-floating-point-arithmetic</guid><category><![CDATA[tips]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Thu, 09 Jan 2020 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720536335440/b02a7922-d0ae-46dd-ae7f-6943f26628cd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong><em>You can find the Chinese version at</em> 從</strong> <a target="_blank" href="https://medium.com/starbugs/see-why-floating-point-error-can-not-be-avoided-from-ieee-754-809720b32175"><strong>IEEE 754 標準來看為什麼浮點誤差是無法避免的</strong></a></p>
</blockquote>
<h3 id="heading-introduction">Introduction</h3>
<p>When people first learn to code, they often encounter floating-point errors. If you haven't experienced this yet, you're very lucky!</p>
<p>For example, in Python, 0.1 + 0.2 does not equal 0.3, and 8.7 / 10 does not equal 0.87 but 0.869999… It's really strange.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720534179733/fde695a7-25c3-424e-9959-c1a915e863e4.webp" alt class="image--center mx-auto" /></p>
<p>However, this is not a bug or a flaw in Python. It's the result of how floating-point numbers are calculated, and this happens in other languages like Node.js too.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720534195039/ba85c649-d4d0-4c2d-b508-11e8fd8a86af.webp" alt class="image--center mx-auto" /></p>
<h3 id="heading-how-computers-store-integers"><strong>How Computers Store Integers</strong></h3>
<p>Before discussing floating-point errors, let's look at how computers represent integers using binary (0s and 1s). For instance, <code>101</code> in binary represents 2² + 2⁰ = 5, and <code>1010</code> represents 2³ + 2¹ = 10.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720536037662/b1becaf6-6698-410b-9438-0507f0049ec9.jpeg" alt class="image--center mx-auto" /></p>
<p>A 32-bit unsigned integer can hold 32 bits, so the smallest value is <code>0000...0000</code> (0), and the largest is <code>1111...1111</code>, which is 2³¹ + 2³⁰ + … + 2¹ + 2⁰ = 4294967295.</p>
<p>Each bit can be either 0 or 1, giving 2³² possible values. <mark>This means any value between 0 and 2³²-1 can be represented without error.</mark></p>
<h3 id="heading-how-about-floating-point-numbers"><strong>How about Floating-Point Numbers</strong></h3>
<p>While there are many integers between 0 and 2³²-1, their number is limited to 2³². Floating-point numbers are different. <mark>In the range of 1 to 10, there are only ten integers but an infinite number of floating-point numbers like 5.1, 5.11, 5.111, etc.</mark></p>
<p>Since a 32-bit space has only 2³² possibilities, fitting all floating-point numbers into this space requires a standard representation, which is where <a target="_blank" href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a> comes in.</p>
<h2 id="heading-ieee-754-standard"><strong>IEEE 754 Standard</strong></h2>
<p>IEEE 754 defines how to represent single (32-bit), double (64-bit), and special values (infinity, NaN) for floating-point numbers.</p>
<h3 id="heading-normalization">Normalization</h3>
<p>For example, to convert <code>8.5</code> to IEEE 754 format, you normalize it by breaking it into <code>8 + 0.5</code>, which is <code>2³ + 1/2¹</code>. In binary, this is <code>1000.1</code>, or <code>1.0001 x 2³</code>, similar to scientific notation in base 10.</p>
<h3 id="heading-single-precision-floating-point"><strong>Single Precision Floating-Point</strong></h3>
<p>In IEEE 754, a 32-bit floating-point number has three parts: sign, exponent, and fraction, adding up to 32 bits.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720536071339/6c9b7bb7-9a2a-48ee-ba98-651d367e1746.jpeg" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Sign</strong>: The leftmost bit indicates the sign (0 for positive, 1 for negative).</p>
</li>
<li><p><strong>Exponent</strong>: The next 8 bits represent the exponent in a biased format (value + 127).</p>
</li>
<li><p><strong>Fraction</strong>: The last 23 bits represent the fractional part (after the decimal point).</p>
</li>
</ul>
<p>For example, 8.5 in 32-bit format is represented as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720535915626/2c2796ab-e677-4ea0-a5a8-b1b948cb9f35.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-when-is-it-inaccurate"><strong>When is it Inaccurate?</strong></h3>
<p><mark>The example of 8.5 can be precisely represented as 2³ + 1/2¹ because both 8 and 0.5 are powers of 2, without precision loss.</mark></p>
<p>However, for 8.9, which cannot be exactly represented as a sum of powers of 2, it must be approximated, resulting in small errors. You can explore these errors using the <a target="_blank" href="https://www.h-schmidt.net/FloatConverter/IEEE754.html">IEEE-754 Floating Point Converter</a>.</p>
<h3 id="heading-double-precision-floating-point"><strong>Double Precision Floating-Point</strong></h3>
<p>To reduce errors, IEEE 754 also defines a 64-bit representation, doubling the size of the fraction part from 23 to 52 bits, thereby increasing precision.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720536101159/b0e913f5-4bef-44b7-aa83-119e63875c2f.jpeg" alt class="image--center mx-auto" /></p>
<p>For instance, while 8.9 still can't be perfectly represented, the error is much smaller in 64-bit format compared to 32-bit.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720535297759/34e5ade4-643d-4ca0-a151-c1ca67059a81.webp" alt class="image--center mx-auto" /></p>
<p>In Python, 1.0 and 0.999...999 are considered equal, as are 123 and 122.999...999, because their difference is too small to be represented in the fraction part.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720535304404/0795e68b-8595-47e4-956e-2f8f142ea71e.webp" alt class="image--center mx-auto" /></p>
<h2 id="heading-solutions"><strong>Solutions</strong></h2>
<p>Since floating-point errors are unavoidable, here are two common ways to handle them:</p>
<h3 id="heading-set-a-maximum-allowable-error-epsilon"><strong>Set a Maximum Allowable Error (epsilon)</strong></h3>
<p>Some languages provide an epsilon value to determine if a result is within an acceptable error range. In Python, epsilon is about 2.2e-16.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720535396586/56c9f0fe-fe02-4bfe-a4e0-90812521ee17.webp" alt class="image--center mx-auto" /></p>
<p>You can rewrite <code>0.1 + 0.2 == 0.3</code> as <code>abs(0.1 + 0.2 - 0.3) &lt;= epsilon</code> to avoid errors in calculations.</p>
<h3 id="heading-use-decimal-calculations">Use Decimal Calculations</h3>
<p><mark>To avoid conversion errors between decimal and binary, use decimal calculations directly.</mark> Python's <code>decimal</code> module can handle this, performing exact decimal arithmetic.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720535511559/ae90ce56-97e0-4bd2-8b68-307ac07df59a.webp" alt class="image--center mx-auto" /></p>
<p>While using decimal arithmetic eliminates floating-point errors, <mark>it is slower because it simulates decimal operations on the CPU, which natively uses binary.</mark></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Floating-point errors are unavoidable, but understanding IEEE 754 can help you manage them. Knowing the format's details can be interesting and useful, allowing you to explain why these errors occur confidently.</p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a></p>
</li>
<li><p><a target="_blank" href="https://www.h-schmidt.net/FloatConverter/IEEE754.html">IEEE-754 Floating Point Converter</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Maximizing Rust Vector Efficiency: Why Initial Capacity Tricks Work]]></title><description><![CDATA[Discover why initial capacity boosts Rust Vectors' performance. Learn how to enhance efficiency and speed up operations with these essential tips.]]></description><link>https://larrylu.dev/maximizing-rust-vector-efficiency-why-initial-capacity-tricks-work</link><guid isPermaLink="true">https://larrylu.dev/maximizing-rust-vector-efficiency-why-initial-capacity-tricks-work</guid><category><![CDATA[Rust]]></category><category><![CDATA[performance]]></category><category><![CDATA[tips]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Mon, 09 Dec 2019 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720341982090/7642f02b-9f29-4d33-8a6b-565f16c336f7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong><em>You can find the Chinese version at</em></strong> <a target="_blank" href="https://medium.com/starbugs/why-you-should-set-initial-capacity-for-rust-vector-4d68a9127abd"><strong>為什麼你應該幫 Rust Vector 加上初始容量</strong></a></p>
</blockquote>
<h3 id="heading-introduction">Introduction</h3>
<p>High-level programming languages usually offer growable arrays, like C++ and Rust's Vectors, Go's Slices, or JavaScript's Arrays. These can change in size and offer push and pop functions to add or remove elements. They're essentially enhanced arrays.</p>
<p>Since growable arrays in different languages work similarly, this discussion isn't limited to Rust Vectors. However, I'll use Rust Vectors as an example because I've been working with Rust recently. If you're not familiar with Rust, don't worry—just look at the example to see how Rust Vectors work.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> vec = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]; <span class="hljs-comment">// [1, 2, 3]</span>
    vec.push(<span class="hljs-number">4</span>);                 <span class="hljs-comment">// [1, 2, 3, 4]</span>
    vec.push(<span class="hljs-number">5</span>);                 <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
    vec.pop();                   <span class="hljs-comment">// [1, 2, 3, 4]</span>
}
</code></pre>
<h3 id="heading-why-vectors-can-grow">Why Vectors Can Grow</h3>
<p>In lower-level languages like C, you must specify a length when allocating memory. Growable arrays like Vectors need to allocate extra space initially to allow for pushing new elements.</p>
<p>For example, if you have a Vector <code>[1, 2, 3]</code>, it might allocate space for 6 integers. The first three slots hold <code>[1, 2, 3]</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720339430312/06162a73-1900-4c4d-88b2-73d26aab5e13.webp" alt class="image--center mx-auto" /></p>
<p>When you run <code>vec.push(4)</code>, it places 4 in the next slot without reallocating memory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720339457174/0d206464-8721-4aac-9f95-f8dc7f383713.webp" alt class="image--center mx-auto" /></p>
<p>But if you keep pushing elements and exceed the initial capacity, Rust will allocate a new memory block twice the size and copy the existing elements over.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720339548525/b7eeb958-92f5-4a65-b39a-ec483a79996d.webp" alt class="image--center mx-auto" /></p>
<p>So, after <code>vec.push(7)</code>, the Vector's capacity becomes 12, giving you 5 more empty slots. If you fill these up, Rust will double the capacity again and copy the numbers over.</p>
<h2 id="heading-small-example-double-function">Small Example: Double function</h2>
<p>Now, consider this <code>double</code> function, which creates a new Vector where each value is double the original. For instance, <code>[1, 2, 3]</code> becomes <code>[2, 4, 6]</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> vec = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
    <span class="hljs-keyword">let</span> vec2 = double(&amp;vec);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, vec);  <span class="hljs-comment">// [1, 2, 3]</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, vec2); <span class="hljs-comment">// [2, 4, 6]</span>
}
</code></pre>
<p>The current implementation declares a new <code>vec2</code> using <code>Vec::new()</code> and pushes each doubled value into <code>vec2</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">double</span></span>(vec: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> vec2 = <span class="hljs-built_in">Vec</span>::new();
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> vec.iter() {
        vec2.push(x * <span class="hljs-number">2</span>);
    }
    <span class="hljs-keyword">return</span> vec2;
}
</code></pre>
<h3 id="heading-whats-the-problem">What's the Problem?</h3>
<p>As mentioned earlier, Vectors allocate extra space, but if it’s insufficient, they reallocate double the previous capacity and copy the data over.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720339924356/6d066735-a523-4798-a986-a88f6df5fd59.jpeg" alt class="image--center mx-auto" /></p>
<p>If you double a Vector of 10,000 elements, you'll perform 10,000 pushes. If these pushes frequently exceed the capacity, the Vector will keep reallocating and copying, making the process time-consuming.</p>
<h3 id="heading-improved-double-function">Improved double function</h3>
<p>To avoid constant memory allocation and copying, Rust provides <code>Vec::with_capacity(cap)</code>, allowing you to set an initial capacity. By reserving enough space at the start, you avoid moving contents around, improving efficiency.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">double2</span></span>(vec: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> vec2 = <span class="hljs-built_in">Vec</span>::with_capacity(vec.len());
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> vec.iter() {
        vec2.push(x * <span class="hljs-number">2</span>);
    }
    <span class="hljs-keyword">return</span> vec2;
}
</code></pre>
<p>The second version is almost the same, except it replaces <code>Vec::new()</code> with <code>Vec::with_capacity(vec.len())</code>, setting the initial capacity to the original Vector's length. This ensures enough space, so you can push without worrying about exceeding capacity.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720340138228/070a02be-dc45-482b-bed1-7c45572b70af.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-performance-comparison">Performance Comparison</h2>
<p>Theoretically, reserving capacity should make it faster, but how much faster? I ran both versions of "double" with a 100,000-element array 1,000 times to get an average.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720340198310/7c7a6ddd-1808-4b43-9124-70bede337b62.webp" alt class="image--center mx-auto" /></p>
<p>The first version took about 273 ms, while the improved version took only 107 ms—about 2.5 times faster. This was compiled in release mode, so it’s close to real-world performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you know why setting an initial capacity for Rust Vectors is important. If you know the final number of elements, like in this example, using an initial capacity speeds up the push operations. If you can't know the exact number but have an estimate, setting an initial capacity can also reduce the number of reallocations.</p>
<p>Even if you don't use Rust, many languages have similar initialization methods, like Go's <code>make([]T, len, cap)</code> and Java's <code>new ArrayList&lt;T&gt;(cap)</code>. The key is understanding how Vectors expand and knowing when to set an initial capacity.</p>
<p>Lastly, while setting an initial capacity speeds up push operations, the overall impact on your program might be small. For significant performance improvements, focus on the architecture, I/O model, algorithms, etc. Simply changing <code>Vec::new()</code> to <code>Vec::with_capacity(cap)</code> won’t suffice.</p>
<p><a target="_blank" href="https://github.com/LarryLuTW/rust-vec-capacity-benchmark/blob/master/src/main.rs">View the example code on GitHub</a></p>
]]></content:encoded></item><item><title><![CDATA[Divide and Conquer: Parallel Computing with Goroutines in Golang]]></title><description><![CDATA[Boost Golang performance with goroutines for parallel computing. Learn task division, multi-core processing, and see performance benchmarks.]]></description><link>https://larrylu.dev/divide-and-conquer-parallel-computing-with-goroutines-in-golang</link><guid isPermaLink="true">https://larrylu.dev/divide-and-conquer-parallel-computing-with-goroutines-in-golang</guid><category><![CDATA[Go Language]]></category><category><![CDATA[backend]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Tue, 06 Nov 2018 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720336780236/8e65b548-22b3-437c-88ca-fbdd23b5f690.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong><em>You can find the Chinese version at</em></strong> <a target="_blank" href="https://larrylu.blog/golang-goroutine-parallel-processing-d382e6d34a14">分而治之 - 在 Golang 使用 Goroutine 進行平行運算</a></p>
</blockquote>
<p>In Golang, starting a goroutine is very simple; you just need one line: <code>go task()</code>. This makes it easy to write concurrent programs. This article will explain how to use goroutines for parallel computing to maximize CPU performance.</p>
<h3 id="heading-what-is-parallel-computing">What is "parallel computing"?</h3>
<p>According to Wikipedia:</p>
<blockquote>
<p>Parallel computing is a type of computation in which many calculations or processes are carried out simultaneously. Large problems can often be divided into smaller ones, which can then be solved at the same time.</p>
</blockquote>
<p>In simple terms, it means <mark>taking a big task and breaking it into smaller tasks</mark>, then handling them in parallel.</p>
<h2 id="heading-todays-big-task-adding-up-the-numbers-in-a-slice">Today's big task: adding up the numbers in a slice.</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720334005856/f00a3fb9-d9d6-4752-82ac-62ad5d05bae0.jpeg" alt class="image--center mx-auto" /></p>
<p>You might think, "What's so hard about summing up numbers in a slice? Even my grandma could do that." So, you quickly write a Sum function, running a loop to add up all the numbers.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Sum</span><span class="hljs-params">(numbers []<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    total := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> _, n := <span class="hljs-keyword">range</span> numbers {
        total += n
    }
    <span class="hljs-keyword">return</span> total
}
</code></pre>
<p>In the test, it took only 500,000 nanoseconds to sum up one million numbers, which is very fast.</p>
<blockquote>
<p>Note: One second equals one billion nanoseconds</p>
</blockquote>
<pre><code class="lang-bash">&gt; go <span class="hljs-built_in">test</span> -bench=^BenchmarkSum$
goos: darwin
goarch: amd64
BenchmarkSum-8 3000 502660 ns/op
</code></pre>
<p>However, because the Sum function above runs on a single thread, it only uses one CPU. <mark>If your computer has multiple CPUs, you could find a way to make them work together.</mark></p>
<h3 id="heading-dual-core-improved-version">Dual-Core Improved Version</h3>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To process large tasks in parallel, we need to break them into smaller tasks.</div>
</div>

<p>For example, if we can split a slice into two halves, let cpu1 add up the left half and cpu2 add up the right half. Then, combine their sums. This should be faster, right?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720334137955/750d68a7-f9b8-4304-b29f-8248a43cf403.jpeg" alt class="image--center mx-auto" /></p>
<p>Following this idea, the code gives the left and right halves to different goroutines to sum up, then uses a channel to add the results together.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">SumTwoParallel</span><span class="hljs-params">(numbers []<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    mid := <span class="hljs-built_in">len</span>(numbers) / <span class="hljs-number">2</span>

    ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)
    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { ch &lt;- Sum(numbers[:mid]) }()
    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { ch &lt;- Sum(numbers[mid:]) }()

    total := &lt;-ch + &lt;-ch
    <span class="hljs-keyword">return</span> total
}
</code></pre>
<p>The benchmark shows it only took 300,000 nanoseconds this time. it's much faster.</p>
<pre><code class="lang-bash">&gt; go <span class="hljs-built_in">test</span> -bench=^BenchmarkSumTwoParallel$
goos: darwin
goarch: amd64
BenchmarkSumTwoParallel-8 5000 300351 ns/op
</code></pre>
<h3 id="heading-multi-core-general-version"><strong>Multi-Core General Version</strong></h3>
<p>The "Dual-Core Improved Version" splits the slice into left and right halves, but with more CPUs, we can split it into more parts.</p>
<p>First, use <code>runtime.NumCPU()</code> to get the number of CPUs. Then, split the slice into N parts, where N is the number of CPUs, and let different goroutines sum each part. Finally, combine all the results into a total. This way, the task is evenly distributed no matter how many CPUs the computer has.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">SumMaxParallel</span><span class="hljs-params">(numbers []<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    nCPU := runtime.NumCPU()
    nNum := <span class="hljs-built_in">len</span>(numbers)

    ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; nCPU; i++ {
        from := i * nNum / nCPU
        to := (i + <span class="hljs-number">1</span>) * nNum / nCPU
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { ch &lt;- Sum(numbers[from:to]) }()
    }

    total := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; nCPU; i++ {
        total += &lt;-ch
    }
    <span class="hljs-keyword">return</span> total
}
</code></pre>
<p>On my 8-core laptop, it took about 160,000 nanoseconds, which is 3x faster compared to the initial 500,000 nanoseconds.</p>
<pre><code class="lang-bash">&gt; go <span class="hljs-built_in">test</span> -bench=^BenchmarkSumMaxParallel$
goos: darwin
goarch: amd64
BenchmarkSumMaxParallel-8 10000 163897 ns/op
</code></pre>
<h2 id="heading-why-is-it-only-three-times-faster">Why is it only three times faster?</h2>
<p>You might think, "For an eight-core computer, splitting the task into eight parts and processing them in parallel should be nearly eight times faster. Why is it only three times faster?"</p>
<p>I was also puzzled by this, so I traced the execution of each goroutine and found two main reasons:</p>
<h3 id="heading-long-wait-time-for-threads-to-start">Long wait time for threads to start</h3>
<p>As shown in the picture below, the program starts with only one main thread. When creating eight goroutines, the system needs some time to start seven more threads. That means it can't start summing immediately with <code>go func(){…}()</code>, causing some delay.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720334766889/2d6d896b-d030-49e8-b93c-17d79bfcb897.webp" alt class="image--center mx-auto" /></p>
<p>But this isn't the fault of goroutines, as they start quickly. If there were a thread pool with pre-started threads, this issue could be solved.</p>
<h3 id="heading-the-summing-task-is-too-simple">The summing task is too simple</h3>
<p>The delay in thread start-up alone shouldn't cause a significant slowdown. The task itself (slice summation) is very simple and runs quickly. So, even a slight delay in thread start-up leads to a big difference in benchmark results.</p>
<p>In the picture below, goroutine 15 took about 350,000 nanoseconds in total, with 230,000 nanoseconds waiting to be scheduled. About two-thirds of the time was spent waiting, making the result slow.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720334932029/0f385c7c-34cd-4439-8a7b-683e2011ab89.webp" alt class="image--center mx-auto" /></p>
<p>If the task were very complex and took a long time to execute, the delay in thread start-up would be relatively smaller and the benchmark results more valuable.</p>
<h2 id="heading-summary">Summary</h2>
<p>This example shows how to split a big task for parallel processing on multiple CPUs. Parallel computing can be used in many areas like merge sort, matrix multiplication, and map reduce. Even though this example is simple, the concept is the same.</p>
<p><mark>When dealing with complex tasks, think about whether you can break them down into smaller tasks to handle separately.</mark></p>
<p>All the code from this article is on <a target="_blank" href="https://github.com/LarryLuTW/go-parallel-computing-example">the GitHub repo</a>. Feel free to clone it to your computer and run the benchmark.</p>
]]></content:encoded></item><item><title><![CDATA[Concurrency in Go: Race Conditions and their Solutions]]></title><description><![CDATA[Learn to handle race conditions in Go using goroutines, explore practical examples, and discover effective solutions with mutex locks and detectors.]]></description><link>https://larrylu.dev/concurrency-in-go-race-conditions-and-their-solutions</link><guid isPermaLink="true">https://larrylu.dev/concurrency-in-go-race-conditions-and-their-solutions</guid><category><![CDATA[Go Language]]></category><category><![CDATA[backend]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Sun, 15 Apr 2018 08:17:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686816860600/21285742-762e-4d50-a3ce-486ae8da1909.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://larrylu.blog/race-condition-in-golang-c49a6e242259">用一個小例子談談 Golang 中的 Race Condition</a>.</p>
</blockquote>
<p>Goroutine is one of the most important features of Go. It allows developers to easily achieve concurrency. Also, It is lightweight, making it feasible to create a substantial number of goroutines without difficulty.</p>
<p>However, if race conditions are not considered when using goroutines, it can lead to incorrect results. This article presents a straightforward example to illustrate situations where race conditions may arise and provides guidance on detecting and resolving it.</p>
<h2 id="heading-race-condition">Race Condition</h2>
<p>According to the definition of Race Condition on <a target="_blank" href="https://en.wikipedia.org/wiki/Race_condition">Wikipedia</a>:</p>
<p><em>A race condition or race hazard is the behavior of electronics, software, or other systems where the output is dependent on the sequence or timing of other uncontrollable events.</em></p>
<p>For example, if there are two ongoing goroutines that both perform operations on the variable <code>a</code> such as <code>a = a * 2</code> and <code>a = a + 1</code>, the different order of these goroutines may result in different values for the variable <code>a</code>. This is a race condition. To prevent race conditions, it is crucial to implement measures that establish a deterministic order, thereby avoiding unpredictable bugs.</p>
<p>Let's consider <a target="_blank" href="https://github.com/LarryLuTW/go-race-condition-demo/blob/master/add_few_times/main.go">the following example</a>, which consists of three steps.</p>
<ol>
<li><p>Set the initial value of the variable <code>a</code> to 0.</p>
</li>
<li><p>Start 3 goroutines that each do <code>a++</code> once.</p>
</li>
<li><p>Use a channel to wait for all three goroutines to complete.</p>
</li>
</ol>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    a := <span class="hljs-number">0</span>
    times := <span class="hljs-number">3</span>
    c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">bool</span>)

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            a++
            c &lt;- <span class="hljs-literal">true</span>
        }()
    }

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        &lt;-c
    }
    fmt.Printf(<span class="hljs-string">"a = %d\n"</span>, a)
}
</code></pre>
<p>If everything goes well, the expected result should be <strong>a = 3</strong>, and it does match the actual output. Now, let's modify the number of iterations to ten thousand:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    a := <span class="hljs-number">0</span>
    times := <span class="hljs-number">10000</span>  <span class="hljs-comment">// &lt;-- HERE</span>
    c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">bool</span>)

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            a++
            c &lt;- <span class="hljs-literal">true</span>
        }()
    }

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        &lt;-c
    }
    fmt.Printf(<span class="hljs-string">"a = %d\n"</span>, a)
}
</code></pre>
<p>Theoretically, we should expect <strong>a = 10000</strong>, but running the code may yield results like <strong>a = 9903</strong>. So weird, we do create ten thousand goroutines and run <code>a++</code> ten thousand times, so why is the result incorrect? It's because a race condition occurred during the <code>a++</code> operation.</p>
<h3 id="heading-why-does-a-result-in-a-race-condition">Why does <code>a++</code> result in a race condition?</h3>
<p>When you write <code>a++</code>, the computer actually performs three steps:</p>
<ol>
<li><p>The CPU retrieves the value of <code>a</code>.</p>
</li>
<li><p>It adds 1 to the retrieved value.</p>
</li>
<li><p>It stores the result back into the variable <code>a</code>.</p>
</li>
</ol>
<p>In case you have a multi-core CPU, the following scenario is possible:</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*usl1WvSboMfHjSWYBGiKQQ.png" alt /></p>
<p><mark>Two CPUs simultaneously retrieve the value of </mark> <code>a</code><mark>, increment it independently and store it back, leading to the variable </mark> <code>a</code> <mark> being incremented only once.</mark> As a result, the output 9903 is smaller than the expected value of 10000.</p>
<h2 id="heading-solution-mutex-lock">Solution: Mutex Lock</h2>
<p>The fundamental reason for this race condition is that "<strong>two goroutines can access the variable 'a' simultaneously.</strong>" To restrict only one goroutine from executing <code>a++</code> at a time, we can use the <a target="_blank" href="https://pkg.go.dev/sync#Mutex">sync.Mutex</a> package.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    a := <span class="hljs-number">0</span>
    times := <span class="hljs-number">10000</span>
    c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">bool</span>)

    <span class="hljs-keyword">var</span> m sync.Mutex   <span class="hljs-comment">// init the lock</span>

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            m.Lock()   <span class="hljs-comment">// acquire lock</span>
            a++
            m.Unlock() <span class="hljs-comment">// release lock</span>
            c &lt;- <span class="hljs-literal">true</span>
        }()
    }

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        &lt;-c
    }
    fmt.Printf(<span class="hljs-string">"a = %d\n"</span>, a)
}
</code></pre>
<p>The term "<strong>Mutex</strong>" stands for <strong>mutual exclusion</strong>, where only one person (goroutine) can hold the lock at a time. <mark>If others attempt to acquire the lock, they will be blocked until the previous holder releases it.</mark> By using a mutex, we ensure that only one goroutine performs 'a++' at any given time, resulting in the correct output of 10000.</p>
<h2 id="heading-how-to-detect-race-conditions">How to detect race conditions:</h2>
<p>In this example, the race condition occurs during <code>a++</code>. However, it may be challenging to identify such issues if you are not familiar with low-level computer operations. Fortunately, Go provides a powerful tool called the <a target="_blank" href="https://go.dev/doc/articles/race_detector">Data Race Detector</a>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    a := <span class="hljs-number">0</span>
    times := <span class="hljs-number">10000</span>
    c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">bool</span>)

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            a++
            c &lt;- <span class="hljs-literal">true</span>
        }()
    }

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; times; i++ {
        &lt;-c
    }
    fmt.Printf(<span class="hljs-string">"a = %d\n"</span>, a)
}
</code></pre>
<p>By running the code with the '-race' flag, the Data Race Detector can help detect potential race conditions. You can clone the <a target="_blank" href="https://github.com/LarryLuTW/go-race-condition-demo/blob/master/add_few_times/main.go">source code</a> from the repository and run it yourself.</p>
<pre><code class="lang-bash">$ go run -race main.go
==================
WARNING: DATA RACE
Read at 0x00c4200a4008 by goroutine 7:
  main.main.func1()
      .../add_few_times/main.go:12 +0x38Previous write at 0x00c4200a4008 by goroutine 6:
  main.main.func1()
      .../add_few_times/main.go:12 +0x4eGoroutine 7 (running) created at:
  main.main()
      .../add_few_times/main.go:11 +0xc1Goroutine 6 (running) created at:
  main.main()
      .../add_few_times/main.go:11 +0xc1
==================
Found 1 data race(s)
<span class="hljs-built_in">exit</span> status 66
</code></pre>
<p>The Race Detector warns about a data race. It indicates that goroutine G7 reads variable <code>a</code> before G6 has written to it, which could result in G7 reading outdated data. This is a possible race condition. Through the Race Detector, you can detect almost all race conditions.</p>
<h2 id="heading-drawbacks-of-using-locks">Drawbacks of using locks</h2>
<h3 id="heading-performance">Performance</h3>
<p>In the previous example, we used a mutex to prevent multiple goroutines from accessing the same variable simultaneously. <mark>However, since there are ten thousand goroutines, when one of them accesses the variable, the other 9999 goroutines are waiting.</mark> This results in no parallelism between them. In comparison, using a loop to increment the variable from 0 to 10000 might be faster.</p>
<p>Therefore, when using locks, it is essential to be cautious and use them only when necessary. Otherwise, the performance of the program may be significantly decreased.</p>
<h3 id="heading-forgetting-to-unlock">Forgetting to unlock</h3>
<p>Sometimes, locking and unlocking is not as simple as in this case. There may be multiple locks, various conditional checks, network requests, and other complexities. In complex scenarios, <mark>there is a possibility of forgetting or delaying the unlock operation, leading to a slow or completely stuck program, causing a </mark> <a target="_blank" href="https://en.wikipedia.org/wiki/Deadlock"><mark>Deadlock</mark></a> <mark> issue.</mark></p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we discussed when race conditions may occur in Go and how to address them. Due to the ease of creating goroutines, it is easy to unintentionally overlook race conditions. Fortunately, Go provides tools like the Race Detector to detect such issues without the need for manual searching.</p>
<p>When I primarily wrote Node.js, I didn't have to worry about race conditions because JavaScript is single-threaded. Tasks are not interrupted halfway through. Also, there are no simultaneous accesses to variables by multiple threads. It was easy to JavaScript write code, but the downside was that time-consuming computations could potentially block the entire program. Each approach has its pros and cons.</p>
<p>Lastly, this article refers to <a target="_blank" href="https://github.com/LarryLuTW/go-race-condition-demo">the source code</a> in this GitHub repository. Feel free to clone it and try it yourself.</p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Race_condition">Race Condition - Wikipedia</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Deadlock">Deadlock - Wikipedia</a></p>
</li>
<li><p><a target="_blank" href="https://go.dev/doc/articles/race_detector">Data Race Detector</a></p>
</li>
<li><p><a target="_blank" href="https://go.dev/blog/waza-talk">Concurrency is not parallelism - The Go Blog</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Sustain Your Data: A Practical Guide to Using Docker Volumes]]></title><description><![CDATA[Discover how to effectively use Docker Volumes for data persistence across containers with this practical guide on Named and Host Volumes.]]></description><link>https://larrylu.dev/sustain-your-data-a-practical-guide-to-using-docker-volumes</link><guid isPermaLink="true">https://larrylu.dev/sustain-your-data-a-practical-guide-to-using-docker-volumes</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Fri, 09 Mar 2018 07:44:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686815046978/4f25e799-5964-4d21-a451-08af8c8c09d3.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://larrylu.blog/using-volumn-to-persist-data-in-container-a3640cc92ce4">Docker 實戰：使用 Volume 保存容器內的數據</a>.</p>
</blockquote>
<p>This is the third article in the Docker Series. If you haven't read the previous article, "<a target="_blank" href="https://larrylu.dev/pushing-your-docker-images-to-docker-hub-a-step-by-step-guide">Pushing Your Docker Images to Docker Hub: A Step-by-Step Guide</a>", I recommend taking a look at it first.</p>
<p>As I mentioned before, each container operates in isolation. This means that <mark>if we need to upgrade the version of MySQL and decide to shut down the running </mark> <strong><mark>mysql:5.5</mark></strong> <mark>container to start a new </mark> <strong><mark>mysql:5.7</mark></strong> <mark>container, the data stored in the database would be lost.</mark> To address this issue, we can utilize volumes to ensure data persistence.</p>
<p>Basically, Volume is utilized to store data within containers. Let's take a look at the following diagram provided.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*NyEkiVdw2MjS41EZxqjcpg.png" alt /></p>
<p>When you use a volume, Docker creates a local storage area on your machine, usually under <code>/var</code>, and establishes a connection between this folder and a specific folder inside the container. <mark>As they are connected, any changes made to the folder within the container will reflect in the local folder. Importantly, </mark> <strong><mark>even if the container is deleted, the data remains intact in the volume</mark></strong><mark>.</mark> This allows us to preserve the container's data.</p>
<h2 id="heading-how-to-use-named-volumn">How to use named volumn</h2>
<h3 id="heading-step-1-creating-a-named-volume">Step 1 - Creating a named volume</h3>
<p>We first create a volume called "db-data". After completion, you will see an additional volume. Docker has now added a folder on your machine for the volume.</p>
<pre><code class="lang-bash">docker volume create --name db-data
docker volume ls
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*L-LLFPxOg4boJi34ZZu9PA.png" alt /></p>
<h3 id="heading-step-2-using-the-volume">Step 2 - Using the volume</h3>
<p>In this example, we are assigning the <code>db-data</code> volume to the <code>/db/data</code> location within the container. Alternatively, you can substitute it with the path where your database stores data. Let's give it a try:</p>
<ol>
<li><p>Initially, confirm that there are no files in /db/data.</p>
</li>
<li><p>Then, create a file named "file" inside the container.</p>
</li>
<li><p>Finally, check if the file exists.</p>
</li>
</ol>
<pre><code class="lang-bash">docker run -v db-data:/db/data -it ubuntu ls -la /db/data
docker run -v db-data:/db/data -it ubuntu touch /db/data/file
docker run -v db-data:/db/data -it ubuntu ls -la /db/data
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*F_bABSWA31tW943APwd35g.png" alt /></p>
<p>It's worth noting that <strong>these three commands are executed in different containers</strong>. This proves that even <strong>when a container is stopped, the data is still preserved in the volume</strong>, and the next container can successfully access the data left by the previous container.</p>
<h2 id="heading-host-volume">Host Volume</h2>
<p>The previous approach, where you create a volume before using it, is called a <strong>Named Volume</strong>. Now, let's introduce another approach called <strong>Host Volume</strong>, which directly connects a specific folder on your machine with a folder inside the container. Let's see a demo:</p>
<ol>
<li><p>Check that there is no package.json inside <code>~/app</code> on local machine.</p>
</li>
<li><p>Connect the <code>~/app</code> folder on your machine with the <code>/app</code> folder inside the container. Then, run npm init inside the container.</p>
</li>
<li><p>Afterward, check if package.json has been created on your machine.</p>
</li>
</ol>
<pre><code class="lang-bash">ls -la app
docker run -v ~/app:/app --workdir /app node:slim npm init -y
ls -la app
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*mCjrJjMq8ZEoonx3rpvXUA.png" alt /></p>
<p>In the above example, <code>package.json</code> is actually generated inside the container. With volumes, you can avoid installing <strong>npm</strong> but still run <code>npm init</code>. Similarly, you can compile C++ source code without installing <code>g++</code>, develop Java programs without installing JDK, and even use MongoDB without installing it directly on your machine. With just Docker installed, the possibilities are endless! 🎉🎉</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article covered two types of volumes. I hope you have gained a good understanding. If you want to explore further, you can refer to the <a target="_blank" href="https://docs.docker.com/storage/volumes/">official documentation</a>. Volumes will become a common practice in the upcoming chapters as we focus on data persistence.</p>
<p>In the next article, we will discuss how to split an application into multiple containers and have them work together to compose your application. If you're interested, feel free to follow along. Thank you!</p>
]]></content:encoded></item><item><title><![CDATA[Pushing Your Docker Images to Docker Hub: A Step-by-Step Guide]]></title><description><![CDATA[Learn to share Docker images via Docker Hub, understand official vs. unofficial images, and explore alternative registries for more privacy and control.]]></description><link>https://larrylu.dev/pushing-your-docker-images-to-docker-hub-a-step-by-step-guide</link><guid isPermaLink="true">https://larrylu.dev/pushing-your-docker-images-to-docker-hub-a-step-by-step-guide</guid><category><![CDATA[Docker]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Sun, 10 Dec 2017 03:06:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686798797076/1ad8b3c6-ae76-4a45-8792-505ce6c8ffba.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://larrylu.blog/share-image-on-dockerhub-ccb7d9b26fa8">Docker 實戰系列：在 Docker Hub 上分享自己的 image</a>.</p>
</blockquote>
<p>After reading the previous article on <a target="_blank" href="https://larrylu.dev/dockerize-your-app-an-introduction-to-docker">Dockerize Your App: An Introduction to Docker</a>, You have learned how to write a Dockerfile and build your own image. But how to share the image with others for their use? That's exactly what this article is about.</p>
<h2 id="heading-docker-registry">Docker Registry</h2>
<p><a target="_blank" href="https://hub.docker.com/search?q=&amp;type=image">Docker Hub</a> is the official Docker Registry. <mark>A Docker Registry is a place where you can pull(download) or push(upload) images.</mark> Once you upload an image to Docker Registry, others can directly pull and use it, eliminating the need for them to build the image from a Dockerfile.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686797416313/3748fa19-03d8-4dfa-b82b-479d43cb784e.webp" alt class="image--center mx-auto" /></p>
<h3 id="heading-official-vs-unofficial-images">Official vs. unofficial images</h3>
<p><mark>Images on Docker Hub are categorized as </mark> <strong><mark>official</mark></strong> <mark>or </mark> <strong><mark>unofficial</mark></strong><mark>.</mark> Official images, such as <a target="_blank" href="https://hub.docker.com/_/ubuntu/">Ubuntu</a> and <a target="_blank" href="https://hub.docker.com/_/mysql/">MySQL</a>, are more reliable in terms of security and quality. To use them, you can simply execute the command <code>docker pull &lt;image&gt;</code>.</p>
<p>On the other hand, images like <a target="_blank" href="https://hub.docker.com/r/larry850806/nodejs-workspace/">larry850806/nodejs-workspace</a> are the ones I built myself. They will have my username as the prefix. To pull such an image, you would use the command <code>docker pull larry850806/nodejs-workspace</code>.</p>
<h2 id="heading-building-and-pushing-to-docker-hub">Building and Pushing to Docker Hub</h2>
<p>In this article, I will tell you how to share your image on Docker Hub. If you don't have a Docker Hub account yet, you can sign up first. We will use "<a target="_blank" href="https://github.com/Larry850806/simple-express-server">simple-express-server</a>" as an example, but the steps can be applied to any other project that can be built into an image.</p>
<h3 id="heading-building-from-dockerfile">Building from Dockerfile</h3>
<p>Since we want to upload the image to Docker Hub, we need to include our username as prefix during the build process. For example, I would use the command <code>docker build -t larry850806/simple-express-server .</code>. After the build, there will be an image named "<strong>larry850806/simple-express-server</strong>" with a total size of 677 MB.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*qGKvosfiFdalqrmwoTRUWQ.png" alt /></p>
<h3 id="heading-login-to-docker-hub">Login to Docker Hub</h3>
<p>Before pushing, we need to log in using <code>docker login</code>. If you have already signed in before, you don't need to do it again as Docker will remember your credentials.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*FYD0icIdIKQ14bLwerlMkQ.png" alt /></p>
<h3 id="heading-push-to-docker-hub">Push to Docker Hub</h3>
<p>Once logged in, you can directly run docker push <code>larry850806/simple-express-server</code> to push the image. You might think, This image is 677 MB, so it will take a long time to push!</p>
<p>However, that's not the case. Remember, the image is built in layers. In this case, the image is based on <code>node:9.2.0</code>. <mark>When you push, only the newly added layers are uploaded. The unchanged layers do not need to be pushed as they can use the existing </mark> <code>node:9.2.0</code> <mark>layers.</mark></p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*WIV53-bx4iRPHhi6cqOHrA.png" alt /></p>
<p>You can see that many layers are <strong>Mounted from library/node</strong>. Only the top two layers need to be pushed. Thus, the push is relatively fast. Once the image is pushed to Docker Hub, it becomes publicly available for others to use.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*EDzNpBJ8pCGlicJw1rRQrw.png" alt /></p>
<h3 id="heading-other-docker-registry">Other Docker Registry</h3>
<p>Although Docker Hub seems powerful and convenient, there are limitations. You can only have one private project on Docker Hub. Any more than that is not allowed.</p>
<p>However, you wouldn't want to make some projects public due to sensitive information such as your code and API keys. Therefore, you either need to pay for additional private projects or use other free Docker registries like <a target="_blank" href="https://canister.io/">Canister</a> or <a target="_blank" href="https://treescale.com/">Treescale</a>. If security is a concern, you can even set up your own registry, but it will require more effort.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is the second article in the series, covering how to push images to Docker Hub. If you want to easily deploy your own project or build an environment like PHP + MySQL to contribute to the community, give it a try.</p>
<p>In the next article, we'll discuss how to share files between containers and the local machine. If you're interested, feel free to follow along. Thank you!</p>
<blockquote>
<p>Continuing with the next post in this series: <a target="_blank" href="https://larrylu.dev/sustain-your-data-a-practical-guide-to-using-docker-volumes">Sustain Your Data: A Practical Guide to Using Docker Volumes</a>.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Dockerize Your App: An Introduction to Docker]]></title><description><![CDATA[Deploy applications effortlessly using Docker. Learn how to Dockerize your Node.js app in this step-by-step guide. No more environmental concerns!]]></description><link>https://larrylu.dev/dockerize-your-app-an-introduction-to-docker</link><guid isPermaLink="true">https://larrylu.dev/dockerize-your-app-an-introduction-to-docker</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Fri, 01 Dec 2017 14:08:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684418820380/2fe0b1e7-e967-43d6-820a-5b73a7d3e454.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://larrylu.blog/step-by-step-dockerize-your-app-ecd8940696f4">Docker 實戰系列：一步一步帶你 dockerize 你的應用</a>.</p>
</blockquote>
<p>Imagine this scenario, you have finished developing your application and are ready to deploy it to the remote machine. However, you find the <strong>server's distribution</strong> is not Ubuntu or CentOS, which you are most familiar with. Moreover, to run the application, you have to first install <strong>system dependencies</strong> such as Node.js and MongoDB manually. This can be quite a hassle! Now is the perfect moment to use <strong>Docker</strong>.</p>
<p>Docker can help you pack the Ubuntu + Node14 + MongoDB environment with your JS code into a <strong>single image</strong>. <mark>This way, you can effortlessly </mark> <strong><mark>run the entire image</mark></strong> <mark>on the remote server without any concerns about environmental issues.</mark></p>
<h2 id="heading-what-is-docker">What is Docker</h2>
<p>Docker is a <strong>lightweight virtualization</strong> technology that can easily package your application and its environment into an image so that you don't have to worry about environmental issues anymore.</p>
<p>The following example demonstrates using Docker to run three separate applications in different containers. Each container provides an <strong>independent</strong> environment, which means that they can have different systems, databases, compilers, etc. For example, <strong>you can run Node 8 in one container and Node 14 in another.</strong></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80o5934vwpsnlg1lkt71.png" alt="Docker use case" /></p>
<h2 id="heading-lets-try-using-docker">Let's try using Docker</h2>
<h3 id="heading-install-docker">Install Docker</h3>
<p>Docker can be run on Linux, macOS, and Windows. You can go to <a target="_blank" href="https://docs.docker.com/get-docker/">the "Get Docker" page</a> and get the version compatible with your OS. After installing Docker, you can run the command <code>docker run hello-world</code> to verify Docker is properly installed.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wu2adgr3t7mc7d7egujf.png" alt="Docker helloworld" /></p>
<h3 id="heading-create-a-ubuntu-environment-using-docker">Create a Ubuntu environment using Docker</h3>
<p>Docker makes it easy to get the desired environment you want. For example, if you need a Ubuntu Bash environment at the moment, you can first obtain the <a target="_blank" href="https://hub.docker.com/_/ubuntu">Ubuntu image</a> from Docker Hub.</p>
<pre><code class="lang-sh">docker pull ubuntu
docker image ls
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sywmpkh544kasu16pq9.png" alt="ubuntu image" /></p>
<p>After preparing the Ubuntu image, you can run a Bash process in a Ubuntu container. The <code>-it</code> option enables <strong>interactive mode</strong> in the container, which allows us to execute commands in Bash.</p>
<pre><code class="lang-sh">docker run -it ubuntu bash
</code></pre>
<p>After getting into the container, you can run the command <code>cat /etc/*release</code> so you can see the Ubuntu version, which is 22.04.2 LTS on my side.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7y0yv75ud1veub8ty4xw.png" alt="ubuntu version" /></p>
<blockquote>
<p>You may be confused <strong>Image</strong> with <strong>Container</strong>. You can think of an Image as the code. They are simply files stored on disk and not currently running. A Container, on the other hand, is a running instance of an Image. Containers use your CPU and memory resources to execute the code contained in the Image.</p>
</blockquote>
<p>In summary, Docker allows you to get the desired environment. Next, I will tell you how to package your application with the environment you want.</p>
<h2 id="heading-how-to-dockerize-an-existing-application">How to Dockerize an existing application</h2>
<p><strong>Dockerize</strong> means to package an application and environment into a Docker image. Once Docker is installed on the target machine, you can simply run the image to deploy the application.</p>
<p>In this post, I'll demonstrate how to dockerize a Node.js application called <a target="_blank" href="https://github.com/LarryLuTW/simple-express-server">simple-express-server</a>. The application is an HTTP server that listens on port 8080 and responds with "Hello World!" when accessed.</p>
<h3 id="heading-step-0-creating-a-dockerfile">Step 0 - Creating a Dockerfile</h3>
<p>In order to package the code and environment together into a single image, we need to write down all the packaging steps in <strong>Dockerfile</strong>. So, let's create an empty <strong>Dockerfile</strong> first.</p>
<pre><code class="lang-plaintext">simple-express-server
├── Dockerfile  &lt;--  HERE
├── README.md
├── index.js
├── node_modules
└── package.json
</code></pre>
<h3 id="heading-step-1-find-a-suitable-base-image">Step 1 - Find a suitable base image</h3>
<p>Docker image is built layer by layer, so we need to find a suitable Base Image on Docker Hub, and then process it into the image we want.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nbb3ay4fapxz4moqso9t.png" alt="image layers" /></p>
<p><mark>Since the project is written in Node.js, we need to find a Node.js environment on Docker Hub.</mark> We can find the <a target="_blank" href="https://hub.docker.com/_/node">official Node image</a> on Docker Hub by searching for "Node.js".</p>
<p>If you want to dockerize an application written in other languages, you can easily find the corresponding image for <a target="_blank" href="https://hub.docker.com/_/python/">Python</a>, <a target="_blank" href="https://hub.docker.com/_/golang/">Golang</a>, etc.</p>
<p>After deciding on the base image, we have to select a version for it. In this case, we're using <code>node:18.15</code>. If you prefer to use the latest version, you can specify <code>node:latest</code>.</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Dockerfile</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">18.15</span>
</code></pre>
<h3 id="heading-step-2-copy-the-source-code-into-the-image">Step 2 - Copy the source code into the image</h3>
<p>After setting up the Node.js environment, the next step is to copy all the required source code into the image. To do this, we'll use the <code>COPY</code> command to copy <code>index.js</code> and <code>package.json</code> into the <code>/app</code> directory within the container.</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">FROM</span> node:<span class="hljs-number">18.15</span>
<span class="hljs-keyword">COPY</span><span class="bash"> index.js package.json /app/</span>
</code></pre>
<h3 id="heading-step-3-install-the-dependencies">Step 3 - Install the dependencies</h3>
<p>After we have the environment and source code in the image, we need to cd to the <code>/app</code> directory and install the dependencies.</p>
<p>First, we use <code>WORKDIR</code> command to cd to <code>/app</code>, and then <code>RUN</code> the command <code>npm install &amp;&amp; npm cache clean --force</code>. The purpose of cleaning the cache is to minimize the size of the resulting image.</p>
<p>If you're writing other languages, you can replace <code>npm install</code> with the corresponding command, such as <code>pip install</code>, to install the dependencies.</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install &amp;&amp; npm cache clean --force</span>
</code></pre>
<h3 id="heading-step-4-specify-the-initial-command">Step 4 - Specify the initial command</h3>
<p>After preparing the environment, source code, and dependencies, the final step is to execute the program. To do this, we use the <code>CMD</code> to specify the <strong>initial command</strong>. Because this Node.js application requires <code>node index.js</code> to start, we'll write down this command to the Dockerfile.</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">FROM</span> node:<span class="hljs-number">18.15</span>
<span class="hljs-keyword">COPY</span><span class="bash"> index.js package.json /app/</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install &amp;&amp; npm cache clean --force</span>
<span class="hljs-keyword">CMD</span><span class="bash"> node index.js</span>
</code></pre>
<h3 id="heading-step-5-build-the-image">Step 5 - Build the image</h3>
<p>After completing the Dockerfile, we can use the command <code>docker build -t simple-express-server .</code> to build the image from the Dockerfile.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b9c9cmzcpym0t2h3p5l.png" alt="build the image" /></p>
<p>Once the building process is complete, you can run <code>docker image ls</code> to view your image named <code>simple-express-server</code>. <strong>The image contains the Node.js environment, application code, dependencies, and the init command.</strong></p>
<h2 id="heading-run-the-image-on-your-laptop">Run the image on your laptop</h2>
<p>Once the image is prepared, we can start the container by running <code>docker run -p 3000:8080 simple-express-server</code>. Inside the container, the command executed is <code>node index.js</code>. The option <code>-p 3000:8080</code> connects port 3000 on your laptop to port 8080 in the container, so that we can access the API server on <code>127.0.0.1:3000</code>.</p>
<p><mark>After the application is dockerized, we can start the API server without having to install Node.js. </mark> <strong><mark>Docker is all we need!</mark></strong></p>
<h3 id="heading-run-in-the-background">Run in the background</h3>
<p>Since <strong>the command previous will block the terminal</strong>, you can add a <code>-d</code> option to run the container in the background. After running the command <code>docker run -d &lt;image&gt;</code>, you will get the container ID. If you want to view logs of the container, just run <code>docker logs -f &lt;container ID&gt;</code>.</p>
<h2 id="heading-summary">Summary</h2>
<p>This post covers the fundamental concepts of Docker and provides a guide to dockerize an existing Node.js application. If you want to learn more about Docker commands, you can check out the <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/docker/">base command</a> and <a target="_blank" href="https://docs.docker.com/engine/reference/builder/">Dockerfile reference</a>.</p>
<p>This is the first post of the Docker series. In the upcoming posts, I will cover topics such as <strong>docker-compose</strong>, <strong>docker swarm,</strong> and <strong>Kubernetes</strong>, Please follow me if you're interested in learning about Docker. Thank you!</p>
<blockquote>
<p>Continuing with the next post in this series: <a target="_blank" href="https://larrylu.dev/pushing-your-docker-images-to-docker-hub-a-step-by-step-guide"><strong>Pushing Your Docker Images to Docker Hub: A Step-by-Step Guide</strong></a><strong>.</strong></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Improving Node.js Server Efficiency with PM2 and Cluster]]></title><description><![CDATA[Maximize Node.js Performance: Harness the power of PM2 to manage processes and set up a cluster. Optimize CPU utilization and enhance server efficiency.]]></description><link>https://larrylu.dev/improving-nodejs-server-efficiency-with-pm2-and-cluster</link><guid isPermaLink="true">https://larrylu.dev/improving-nodejs-server-efficiency-with-pm2-and-cluster</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Tue, 28 Nov 2017 09:07:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684400740264/c1ed53dd-9f41-4aac-a467-cefe0ff3be89.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://medium.com/@larry850806/nodejs-pm2-cluster-455ffbd7671">使用 pm2 啟動 Node.js cluster 以提升效能</a>.</p>
</blockquote>
<p>PM2 is a useful tool to manage Node.js processes, which allows us to set up the Node.js cluster to utilize the CPUs. In this post, I will introduce what PM2 is and why it is essential for Node.js applications.</p>
<h2 id="heading-the-disadvantage-of-nodejs">The disadvantage of Node.js</h2>
<p>Node.js implements the <strong>Asynchronous I/O</strong> using a thread pool. When a Node.js application runs, it can use multiple threads. However, the JavaScript runtime in Node.js is <strong>single-threaded</strong> and can only operate on a single CPU. As a result, some CPUs may be overloaded while others are idle at times.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/218kl8zkl0mbn3ja4275.gif" alt="a CPU is overloaded" /></p>
<h2 id="heading-the-solution-clustering">The Solution: Clustering</h2>
<p>If each Node.js process can only run on a single CPU core, why not create more Node.js processes? The problem then becomes how to make these processes listen on the same port. To solve this problem, Node.js provides an official <a target="_blank" href="https://nodejs.org/api/cluster.html#cluster_cluster">cluster</a> module, and the document says:</p>
<blockquote>
<p>A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load. The cluster module allows easy creation of child processes that all share server ports.</p>
</blockquote>
<p>In short, to maximize CPU usage, the <strong>cluster</strong> module allows you to create multiple child processes as workers and listen on the same port.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fx3bdkor7a1sibzyhlkq.png" alt="cluster mode" class="image--center mx-auto" /></p>
<p>As shown in the picture above, <mark>the master process listens on the port and delegates the tasks to the workers. Since there are multiple workers, they can use as much CPU as possible.</mark></p>
<h2 id="heading-pm2-the-simplest-way-to-manage-nodejs-processes">PM2: The simplest way to manage Node.js processes</h2>
<p>Even though there is a cluster module, we still need to handle many things such as auto-restart and load balancing by ourselves. But with PM2, we don't have to worry about these details.</p>
<h3 id="heading-how-to-install-pm2">How to install PM2</h3>
<p>It's easy to install PM2, we can just install it globally.</p>
<pre><code class="lang-sh">npm install pm2 -g
</code></pre>
<p>Once PM2 is installed, we can write a basic HTTP server that listens on port 3000. When a request comes in, it will do something and respond with "Hello World". You can find the code in the <a target="_blank" href="https://github.com/LarryLuTW/pm2-cluster-example/blob/master/index.js">Github repository</a>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> app = express()app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    doSomething()
    res.send(<span class="hljs-string">'Hello World'</span>)
  }, <span class="hljs-number">300</span>)
})app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>Instead of running <code>node index.js</code> to start a single server, now we can use PM2 to run the server in cluster mode by running the command <code>pm2 start -i 4 --name server index.js</code>. Here, The option <code>-i 4</code> indicates that we want to create 4 worker processes.</p>
<p>Once the cluster is up, the output should look similar to the screenshot below. You can access the HTTP server by navigating to <a target="_blank" href="http://localhost:3000/">http://localhost:3000/</a> in a browser.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rdp456975tnb7v996a4.png" alt="server in cluster mode" class="image--center mx-auto" /></p>
<p>The process of shutting down the cluster is also simple. All you need to do is execute the command <code>pm2 delete server</code>. For additional commands and further details, you can refer to the <a target="_blank" href="https://pm2.keymetrics.io/docs/usage/quick-start/">official document</a>.</p>
<h2 id="heading-measuring-performance">Measuring Performance</h2>
<p>Does PM2 really enhance performance? Let's install <a target="_blank" href="https://github.com/alexfernandez/loadtest">loadtest</a> to measure the performance. You can also try it yourself with the <a target="_blank" href="https://github.com/LarryLuTW/pm2-cluster-example">source code</a>.</p>
<p>After installing loadtest, we will use the following command to test the server's maximum load. The option <code>-n 1000 -c 100</code> specifies that there are a total of 1000 requests, with a maximum of 100 concurrent requests.</p>
<pre><code class="lang-sh">npm i loadtest -g
loadtest -n 1000 -c 100 http://localhost:3000/
</code></pre>
<h3 id="heading-comparison-of-the-results">Comparison of the Results</h3>
<p>By running <code>node index.js</code> to start a server instance, the average latency of all requests is 1668ms.</p>
<pre><code class="lang-plaintext">INFO Target URL: http://localhost:3000/
INFO Max requests: 1000
INFO Concurrency level: 100
INFO
INFO Completed requests: 1000
INFO Total time: 17.410050329 s
INFO Requests per second: 57
INFO Mean latency: 1668.1 ms
</code></pre>
<p>However, if we launch the cluster with <code>pm2 start -i 4 --name server index.js</code>, the latency will be reduced to 929ms.</p>
<pre><code class="lang-plaintext">INFO Target URL: http://localhost:3000/
INFO Max requests: 1000
INFO Concurrency level: 100
INFO
INFO Completed requests: 1000
INFO Total time: 9.901042633000001 s
INFO Requests per second: 101
INFO Mean latency: 929.9 ms
</code></pre>
<p>According to the results, we can observe that the time required to consume 1000 requests decreased from 17.4s to 9.9s. Additionally, The requests per second are improved from 57 to 101, representing a <strong>45% performance improvement</strong>.</p>
<p><mark>Most importantly, All you need to do is </mark> <strong><mark>use PM2 to start your server</mark></strong> <mark> and you can get the performance improvement!</mark></p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we have used PM2 to improve the performance of a Node.js server. However, Since <strong>Node.js is not good at CPU-intensive tasks such as encrypting and encoding</strong>, if the performance is still too low even after using PM2, you might want to consider rewriting the service in other languages like C++, Golang, or Rust.</p>
<p>This post is a brief introduction to PM2. In addition to clustering, PM2 also provides several other features. If you're interested in learning more about PM2, please refer to the <a target="_blank" href="https://pm2.keymetrics.io/">official website</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How VSCode Became the Ultimate Editor for Web Developers]]></title><description><![CDATA[Unleash the Power of VSCode: 10 Reasons Why It's the Preferred Code Editor. Explore its color picker, Git integration, code snippets, and more!]]></description><link>https://larrylu.dev/how-vscode-became-the-ultimate-editor-for-web-developers</link><guid isPermaLink="true">https://larrylu.dev/how-vscode-became-the-ultimate-editor-for-web-developers</guid><category><![CDATA[vscode]]></category><category><![CDATA[editor]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Fri, 10 Nov 2017 08:55:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684399882666/77068191-47cc-4b1f-b407-6b120e893665.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version at <a target="_blank" href="https://larrylu.blog/vscode-1b6f24e082ba">新一代的編輯器 — VSCode</a>.</p>
</blockquote>
<p>There is a proverb that says, <strong><em>"If a workman wishes to do a good job, he must first sharpen his tools."</em></strong> For programmers, having a useful editor is crucial. Since many of my friends have asked me about which editor to choose, I'm writing this article to explain why I prefer to use <a target="_blank" href="https://code.visualstudio.com/">VSCode</a>.</p>
<h2 id="heading-ten-reasons-why-i-think-vscode-is-very-powerful">Ten reasons why I think VSCode is very powerful</h2>
<h3 id="heading-1-color-picker">1. Color Picker</h3>
<p>When you have the color code, but don't know what the color looks like, or if you want to pick a suitable color but don't know where to find the palette, you can use the built-in Color Picker in VSCode.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfq6wz3v1i1v58e4imy7.png" alt="Color Picker" /></p>
<h3 id="heading-2-git-integration">2. Git Integration</h3>
<p>Still using <code>git diff</code> command to view changes?</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16a3pt2pi145i967t2hb.png" alt="Git1" /></p>
<p>You can view them directly with better UI in VSCode.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vull6qcztf5nwwwhzxbo.png" alt="Git2" /></p>
<h3 id="heading-3-built-in-emmet">3. Built-in Emmet</h3>
<p>VSCode has a built-in <a target="_blank" href="https://docs.emmet.io/abbreviations/syntax/"><strong>Emmet</strong></a> feature that <strong>speeds up writing HTML</strong>. and makes you look more like a professional developer!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aghhwgu099ogh9iifrgf.gif" alt="Emmet Expansion" /></p>
<h3 id="heading-4-quickly-jump-to-the-file-you-are-looking-for-in-just-a-moment">4. Quickly jump to the file you are looking for in just a moment</h3>
<p>Press <code>&lt;Cmd/Ctrl&gt; + P</code> to quickly jump to the file with a given filename.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb9c85k1jlqqd4l3lsiu.gif" alt="Jump to file by filename" /></p>
<p>Use <code>Cmd/Ctrl + Click</code> to navigate to the imported script.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4lkqt05yodo71tuqnew.gif" alt="Jump to file by reference" /></p>
<h3 id="heading-5-create-your-own-code-snippets">5. Create your own <strong>Code Snippets</strong></h3>
<p>Write code more efficiently with handy code snippets like <code>this.setState()</code> in React.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s653s7q6px64tv5rbjb.gif" alt="Custom code snippet" /></p>
<h3 id="heading-6-distinctive-icons">6. Distinctive icons</h3>
<p>There are different icons for different kinds of files, which making it easy to distinguish files in a glimpse.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4462nzfxlobdbgptaq55.png" alt="Icon" /></p>
<h3 id="heading-7-powerful-intellisense">7. Powerful Intellisense</h3>
<p>VSCode provides information on the parameter name, and type, which is very useful!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndilqdgkegjnhbblmiw5.png" alt="show property name" /></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6bdsbo1tcx3vwhgvky1s.png" alt="show parameter name" /></p>
<h3 id="heading-8-multi-cursor">8. Multi Cursor</h3>
<p>The multi-cursor feature allows you to edit multiple places at the same time.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r355mkqiyshm6wp82sn0.gif" alt="multi cursor editting" /></p>
<h3 id="heading-9-auto-formatting">9. Auto Formatting</h3>
<p>You don't have to worry about the formatting and indentation because VSCode will do it automatically for you. If your team has a style guide, you can also do the formatting with ESLint.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1rs1bmxb5v3nmul3xbo.gif" alt="Auto Formatting" /></p>
<h3 id="heading-10-debug">10. Debug</h3>
<p>VSCode allows you to set breakpoints while debugging, which makes it easier to see the call stack and check the value of variables.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb8owl9ab0k6i6lil7by.png" alt="breakpoint" /></p>
<h2 id="heading-mature-community">Mature Community</h2>
<p>Along with its powerful built-in features, VSCode also has a mature developer community, with many free plugins and themes. Additionally, VSCode receives frequent updates.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh8z4ic0rnaiqvkdno0i.png" alt="extensions" /></p>
<h2 id="heading-compare-with-other-editors">Compare with other editors</h2>
<h3 id="heading-vim">Vim</h3>
<p>I used Vim for a long time before discovering VSCode. While Vim allows extensive customization, its steep learning curve and numerous shortcuts can be challenging. Nevertheless, Vim is still a good editor and its seamless integration with <a target="_blank" href="https://dev.to/larrylutw/master-the-art-of-terminal-session-management-with-tmux-4dm8">tmux</a> provide a smooth development experience.</p>
<p>To get the best of both worlds, I now use the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=vscodevim.vim">Vim extension</a> for VSCode.</p>
<h3 id="heading-sublime">Sublime</h3>
<p>I only used Sublime for a short time. What I liked about it was the convenience of its package manager and fast startup time. However, it had some drawbacks such as the low update frequency and not being open-sourced. This means that developers can't fix bugs by submitting PRs.</p>
<p>If you're using Sublime and want to try out VSCode, you can consider using the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings">Sublime Keymap extension</a>. Although I haven't used it yet, the reviews are pretty positive.</p>
<hr />
<p>If you're still hesitating about whether to use VSCode, I highly recommend it. In my opinion, it's the most successful product that Microsoft released.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/65ll6097o4gshr60ejgm.jpeg" alt="Microsoft love Linux" /></p>
<p>If you think some awesome features aren't mentioned here, please feel free to comment and I'll add them to the post!</p>
]]></content:encoded></item><item><title><![CDATA[Boost Productivity with tmux: Master Terminal Sessions]]></title><description><![CDATA[Supercharge productivity with tmux: Master terminal session management, multi-windows, panes, and session saving in this comprehensive guide.]]></description><link>https://larrylu.dev/boost-productivity-with-tmux-master-terminal-sessions</link><guid isPermaLink="true">https://larrylu.dev/boost-productivity-with-tmux-master-terminal-sessions</guid><category><![CDATA[terminal]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[tmux]]></category><dc:creator><![CDATA[Larry Lu]]></dc:creator><pubDate>Thu, 02 Nov 2017 12:20:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684325660931/28d7c9cf-9f16-4f99-a009-dd9dd0b28d6d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>You can find the Chinese version of this article at <a target="_blank" href="https://medium.com/larry-blog/tmux-33a24e595fbc">終端機 session 管理神器 - tmux</a>.</p>
</blockquote>
<p>As a developer, you should be familiar with the Terminal. Whether you want to create git branches, run the scripts, or ssh to the remote machine, you will need to use the Terminal.</p>
<p>I'd like to introduce you to a great tool called <strong>tmux</strong>. It's a terminal multiplexer with many useful features like <strong>multi-windows</strong>, <strong>window panes,</strong> and <strong>session saving</strong>. Most importantly, tmux can make your terminal stylish and <strong>professional</strong> even if you're not doing anything.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684324197088/0cd3b6f3-6743-48ea-85bf-88212ba0522b.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-to-install-tmux">How to install tmux</h2>
<p>On <strong>Mac OS</strong>, you need to first install <a target="_blank" href="https://brew.sh"><strong>Homebrew</strong></a>, and then use it to install tmux with the following command.</p>
<pre><code class="lang-bash">brew install tmux
</code></pre>
<p>On Debian/Ubuntu Linux, simply run the following command.</p>
<pre><code class="lang-bash">sudo apt-get install tmux
</code></pre>
<p>Once you've installed tmux, run the command <code>tmux</code> and you will see a <strong>green status bar</strong> appear at the bottom of the terminal.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684324350450/71e853fc-8b03-4930-83c3-1dc32ca2ead0.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-basic-concepts-of-tmux">Basic Concepts of tmux</h2>
<h3 id="heading-session">session</h3>
<p>Every time you run <code>tmux</code>, a new independent session is created.</p>
<h3 id="heading-window">window</h3>
<p>A window refers to the entire screen as shown in the screenshot below, and there can be multiple windows in a session.</p>
<h3 id="heading-pane">pane</h3>
<p>As shown in the following screenshot, a window can be split into multiple panes. This functionality is typically used to monitor numerous programs simultaneously.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684324358039/699ca642-0fb1-4fcc-b239-c6a7130b43f7.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-basic-keybindings">Basic Keybindings</h2>
<p>When using tmux, you must press <strong>the prefix</strong> key before any keybinding. By default, the prefix is set to <code>&lt;Ctrl+b&gt;</code>.</p>
<h3 id="heading-pane-1">Pane</h3>
<p>Let's try the keybinding together!</p>
<ul>
<li><p><code>&lt;Ctrl+b&gt; + "</code>: Split pane with vertical layout</p>
</li>
<li><p><code>&lt;Ctrl+b&gt; + %</code>: Split pane with horizontal layout</p>
</li>
<li><p><code>&lt;Ctrl+b&gt; + &lt;Arrow Key&gt;</code>: Switch to other panes</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684393345326/3daebe44-0f39-411c-bfa2-ae76acef25cd.gif" alt class="image--center mx-auto" /></p>
<ul>
<li><p><code>&lt;Ctrl+b&gt; + &lt;Space&gt;</code>: Toggle between pane layouts</p>
</li>
<li><p><code>&lt;Ctrl+b&gt; + x</code>: Close the current pane</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684393372828/d2e3088b-502d-45ac-a876-b026da232a48.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-session-1">Session</h3>
<ul>
<li><p><code>&lt;Ctrl+b&gt; + d</code>: Detach from the current session</p>
</li>
<li><p><code>$ tmux at</code>: Attach to the last session</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684393381790/7d440f9f-b00b-4a85-959a-e407469b60e3.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-common-scenarios">Common scenarios</h2>
<h3 id="heading-scenario-1-running-a-program-and-monitoring-the-cpu-usage-simultaneously">Scenario 1 - Running a program and Monitoring the CPU usage simultaneously</h3>
<p>This is the most common scenario for me. I usually use <strong>two panes</strong> to run a program and display the top/htop result simultaneously.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684324788304/e60cc056-e811-4f87-8b6d-3fa5e06ca01f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-scenario-2-writing-a-program-in-vim-with-real-time-results">Scenario 2 - Writing a program in Vim with Real-Time results</h3>
<p>This scenario is similar to the previous one. You can create a small pane to run the program while editing the source with Vim. If you're using a tool like <strong>nodemon</strong>, it will automatically re-run the script when you update it, so you don't need to leave Vim.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684324794821/edf0f060-c1c2-4b09-93f9-9ab06ceeb6f0.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-scenario-3-keeping-remote-ssh-sessions-with-tmux">Scenario 3 - Keeping remote SSH sessions with tmux</h3>
<p>Without tmux, the command will stop running if you run a command on a remote machine using SSH but the connection is lost.</p>
<p>To avoid this problem, you can install tmux on the remote machine. With a tmux session, even if your ssh connection is lost, your program will continue to run because <strong>it's in the tmux session</strong>.</p>
<h2 id="heading-summary">Summary</h2>
<p>The article is a simple introduction to tmux. As a tool I can't develop without, I want to share this super tool with you through this article.</p>
<p>Since this article is only an introduction for beginners, I didn't list all the commands and keybindings here. If you'd like to learn more about tmux, you can check out <a target="_blank" href="https://tmuxcheatsheet.com/">this cheat sheet</a>. I hope that using tmux can make your development more efficient, and also make your terminal look super-cool!</p>
]]></content:encoded></item></channel></rss>