<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by the korean guy on Medium]]></title>
        <description><![CDATA[Stories by the korean guy on Medium]]></description>
        <link>https://medium.com/@thekoreanguy?source=rss-f72b2d8b11bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by the korean guy on Medium</title>
            <link>https://medium.com/@thekoreanguy?source=rss-f72b2d8b11bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:54:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thekoreanguy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is the best logger in Go?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">There are many logger implements in Go including built-in log.</p><p class="medium-feed-link"><a href="https://thekoreanguy.medium.com/what-is-the-best-logger-in-go-396b1bfe4f01?source=rss-f72b2d8b11bc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://thekoreanguy.medium.com/what-is-the-best-logger-in-go-396b1bfe4f01?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/396b1bfe4f01</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[heap]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 12:31:13 GMT</pubDate>
            <atom:updated>2024-08-26T12:31:13.269Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Is RWMutex better than Mutex in Go?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">In Go, there are two main methods for implementing locking. The first is to use sync.Mutex with its Lock and Unlock methods. This method&#x2026;</p><p class="medium-feed-link"><a href="https://thekoreanguy.medium.com/is-rwmutex-better-than-mutex-in-go-b117f671f17b?source=rss-f72b2d8b11bc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://thekoreanguy.medium.com/is-rwmutex-better-than-mutex-in-go-b117f671f17b?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b117f671f17b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 12:45:43 GMT</pubDate>
            <atom:updated>2024-08-25T12:45:43.334Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to use iter in Go 1.23]]></title>
            <link>https://thekoreanguy.medium.com/how-to-use-iter-in-go-1-23-99f8bb65c6db?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f8bb65c6db</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[iteration]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 13:03:22 GMT</pubDate>
            <atom:updated>2024-08-13T13:03:22.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Iterator in Go?</h3><p>In development terminology, an “iterator” refers to an object or interface that provides sequential access to elements within a collection (e.g., arrays, lists, trees, etc.). An iterator helps in processing or traversing through the elements of a collection by visiting each element one at a time.</p><p>In Go, instead of using a direct iterator pattern, the range keyword is primarily used to iterate over collections such as slices or maps.</p><h3>How to use Iterator in Go?</h3><p><a href="https://pkg.go.dev/iter"><strong>iter</strong></a><strong> is a packge </strong>officially introduced in Go 1.23 for iterating over sequences. However, by setting <a href="https://github.com/golang/go/blob/go1.22.0/src/iter/iter.go#L5">GOEXPERIMENT=rangefunc</a> and using go build or go test, it is possible to temporarily use this feature in version 1.22 as well.</p><p>Therefore, you can either use the Go 1.22.x version with the experimental feature, the 1.23 release candidate, or the official 1.23 version that will be released in August.</p><h3>How is the iter package implemented?</h3><p><a href="https://github.com/golang/go/blob/go1.22.0/src/iter/iter.go">iter</a> package is so simple, it includes the following functions and types.</p><pre>type Seq[V any] func(yield func(V) bool)<br>type Seq2[K, V any] func(yield func(K, V) bool)<br>type coro struct{}<br><br>//go:linkname newcoro runtime.newcoro<br>func newcoro(func(*coro)) *coro<br><br>//go:linkname coroswitch runtime.coroswitch<br>func coroswitch(*coro)<br>func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func())<br>func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func())</pre><p>Today, we’ll take a brief look at Seq and Seq2. You can find a simple example of how to use this <a href="https://pkg.go.dev/iter#hdr-Mutation">here</a>.</p><h3>How to use iter.Seq, iter.Seq2?</h3><p>By implement functions that return these types, you can iterate over your own custom sequences.</p><p>Let’s look at an example of a simple ordered map implementation (note: in practice, an ordered map is not implemented this simply).</p><h4><strong>With no iter.Seq</strong></h4><pre>package ordered_map<br><br>type OrderedMap[K comparable, V any] struct {<br> keys  []K<br> items map[K]V<br>}<br><br>func New[K comparable, V any](capacity int) *OrderedMap[K, V] {<br> return &amp;OrderedMap[K, V]{<br>  keys:  make([]K, 0, capacity),<br>  items: make(map[K]V, capacity),<br> }<br>}<br><br>// Add new items by key, value<br>func (om *OrderedMap[K, V]) Add(k K, v V) {<br> om.keys = append(om.keys, k)<br> om.items[k] = v<br>}<br><br>// Get present item by key<br>func (om *OrderedMap[K, V]) Get(k K) V {<br> return om.items[k]<br>}<br><br>// Retrieve all keys for iteration.<br>func (om *OrderedMap[K, V]) Keys() []K {<br> return om.keys<br>}</pre><p>With the implementation described above, if you want to insert some elements and then retrieve all elements in order, you would need to write the code as shown below.</p><pre><br>type MyStruct struct {<br> id   int<br> name string<br>}<br><br>func (ms MyStruct) String() string {<br> return fmt.Sprintf(&quot;ID: %d, Name: %s&quot;, ms.id, ms.name)<br>}<br><br>func TestOrderedMap(t *testing.T) {<br> t.Run(&quot;print all elements in order.&quot;, func(t *testing.T) {<br>  om := ordered_map.New[string, MyStruct](10)<br>  om.Add(&quot;key1&quot;, MyStruct{id: 1, name: &quot;test1&quot;})<br>  om.Add(&quot;key3&quot;, MyStruct{id: 3, name: &quot;test3&quot;})<br>  om.Add(&quot;key2&quot;, MyStruct{id: 2, name: &quot;test2&quot;})<br><br>  for _, k := range om.Keys() {<br>   fmt.Printf(&quot;Value: %s\n&quot;, om.Get(k))<br>  }<br> })<br>}</pre><p>First, retrieve all the keys, then use om.Get(k) to access the OrderedMap again and list the values.</p><h4>What if you use iter.Seq?</h4><p><strong>When you only need value</strong></p><pre>// only iterate values when use this function<br>func (om *OrderedMap[K, V]) Values() iter.Seq[V] {<br> return func(yield func(V) bool) {<br>  for _, k := range om.keys {<br>   if !yield(om.Get(k)) {<br>    return<br>   }<br>  }<br> }<br>}<br><br>// ...<br><br> t.Run(&quot;print all elements in order using iter.Seq.&quot;, func(t *testing.T) {<br>  om := ordered_map.New[string, MyStruct](10)<br>  om.Add(&quot;key1&quot;, MyStruct{id: 1, name: &quot;test1&quot;})<br>  om.Add(&quot;key3&quot;, MyStruct{id: 3, name: &quot;test3&quot;})<br>  om.Add(&quot;key2&quot;, MyStruct{id: 2, name: &quot;test2&quot;})<br><br>  for v := range om.Values() {<br>   fmt.Printf(&quot;Values: %s\n&quot;, v)<br>  }<br> })</pre><p><strong>When you need key with value</strong></p><pre>// iterate key and value<br>func (om *OrderedMap[K, V]) KeyValues() iter.Seq2[K, V] {<br>    return func(yield func(K, V) bool) {<br>       for _, k := range om.keys {<br>          if !yield(k, om.Get(k)) {<br>             return<br>          }<br>       }<br>    }<br>}<br>// ...<br><br>t.Run(&quot;print all keys and elements in order using iter.Seq.&quot;, func(t *testing.T) {<br>  om := ordered_map.New[string, MyStruct](10)<br>  om.Add(&quot;key1&quot;, MyStruct{id: 1, name: &quot;test1&quot;})<br>  om.Add(&quot;key3&quot;, MyStruct{id: 3, name: &quot;test3&quot;})<br>  om.Add(&quot;key2&quot;, MyStruct{id: 2, name: &quot;test2&quot;})<br><br>  for k, v := range om.KeyValues() {<br>   fmt.Printf(&quot;Key: %s | Values: %s\n&quot;, k, v)<br>  }<br> })</pre><h4>Another Case</h4><p>If you want to iterate over only specific fields in a struct, you can do it like this.</p><pre>type MyStructs []MyStruct<br><br>func (ms MyStructs) Names() iter.Seq[string] {<br> return func(yield func(string) bool) {<br>  for _, s := range ms {<br>   if !yield(s.name) {<br>    return<br>   }<br>  }<br> }<br>}<br><br>type MyStruct struct {<br> id   int<br> name string<br>}<br><br> t.Run(&quot;print only name in struct&quot;, func(t *testing.T) {<br>  var myStructs MyStructs = MyStructs{<br>   MyStruct{id: 1, name: &quot;test1&quot;},<br>   MyStruct{id: 3, name: &quot;test3&quot;},<br>   MyStruct{id: 2, name: &quot;test2&quot;},<br>  }<br>  for name := range myStructs.Names() {<br>   fmt.Printf(&quot;Name: %s\n&quot;, name)<br>  }<br> })</pre><h3>Conclsion</h3><p>While the example above might not be ideal, with Go 1.23, the iter package allows for more diverse operations, including iterating over specific fields of a struct. As a beginner, I can&#39;t fully predict how extensively it will be used, but I hope it inspires someone to implement various data structures. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f8bb65c6db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Increase Slice Capacity in Go]]></title>
            <link>https://thekoreanguy.medium.com/how-does-the-capacity-change-when-you-append-to-a-slice-in-go-46289dad4730?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/46289dad4730</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[gopher]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 11:31:25 GMT</pubDate>
            <atom:updated>2024-08-01T00:27:46.558Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you know what happens when you add a new element to a slice where len == cap?</p><p>Most Gophers would confidently answer that the capacity doubles, new space is allocated, the slice values are copied, and the slice header pointer is updated. This is actually correct.</p><pre>func TestAppendSlice(t *testing.T) {<br> s := make([]int, 2, 3)<br> s = append(s, 0)<br> fmt.Println(&quot;Capacity: &quot;, cap(s), &quot;Pointer: &quot;, unsafe.Pointer(&amp;s[0]))<br> s = append(s, 0)<br> fmt.Println(&quot;Capacity: &quot;, cap(s), &quot;Pointer: &quot;, unsafe.Pointer(&amp;s[0]))<br>}<br><br>// Capacity:  3 Pointer:  0xc00002a5d0<br>// Capacity:  6 Pointer:  0xc00002e750</pre><p>As we can see, the address of s[0] has changed, indicating that the slice has been allocated to a new space and its pointer has been updated. Additionally, the capacity has doubled.</p><p>In fact, that’s only half correct. What if we change int to int16? Let&#39;s see what happens:</p><pre>func TestAppendSlice(t *testing.T) {<br> s := make([]int16, 2, 3)<br> s = append(s, 0)<br> fmt.Println(&quot;Capacity: &quot;, cap(s), &quot;Pointer: &quot;, unsafe.Pointer(&amp;s[0]))<br> s = append(s, 0)<br> fmt.Println(&quot;Capacity: &quot;, cap(s), &quot;Pointer: &quot;, unsafe.Pointer(&amp;s[0]))<br>}<br><br>// Capacity:  3 Pointer:  0xc000015b30<br>// Capacity:  8 Pointer:  0xc000015b38</pre><p>We can observe that the capacity changed to 8 instead of doubling. Why does the capacity change this way? Is it just assigned an arbitrary value?</p><p>How does a slice become so larger?</p><p>The secret behind this can be found in <a href="https://github.com/golang/go/blob/release-branch.go1.23/src/runtime/slice.go#L177">growslice</a>.</p><p>First, growslice calculates the new capacity, newcap, using the following method:</p><pre>newcap := nextslicecap(newLen, oldCap)</pre><p>The nextslicecap(newLen, oldCap int) int function is implemented <a href="https://github.com/golang/go/blob/release-branch.go1.23/src/runtime/slice.go#L289">here</a>, and the code is as follows:</p><pre>func nextslicecap(newLen, oldCap int) int {<br> newcap := oldCap<br> doublecap := newcap + newcap<br> if newLen &gt; doublecap {<br>  return newLen<br> }<br><br> const threshold = 256<br> if oldCap &lt; threshold {<br>  return doublecap<br> }<br> for {<br>  // Transition from growing 2x for small slices<br>  // to growing 1.25x for large slices. This formula<br>  // gives a smooth-ish transition between the two.<br>  newcap += (newcap + 3*threshold) &gt;&gt; 2<br><br>  // We need to check `newcap &gt;= newLen` and whether `newcap` overflowed.<br>  // newLen is guaranteed to be larger than zero, hence<br>  // when newcap overflows then `uint(newcap) &gt; uint(newLen)`.<br>  // This allows to check for both with the same comparison.<br>  if uint(newcap) &gt;= uint(newLen) {<br>   break<br>  }<br> }<br><br> // Set newcap to the requested cap when<br> // the newcap calculation overflowed.<br> if newcap &lt;= 0 {<br>  return newLen<br> }<br> return newcap<br>}</pre><p>As you might know, up to a certain threshold (which changed from <a href="https://github.com/golang/go/blob/go1.17.9/src/runtime/slice.go#L186">1024</a> to <a href="https://github.com/golang/go/blob/go1.18/src/runtime/slice.go#L193">256 in Go 1.18</a>), the capacity is doubled. Beyond that threshold, the capacity increases by 1.25 times.</p><p>If it were returned as is, what we know would be accurate. However, unfortunately, this value undergoes further post-processing.</p><p>The post-processing code is as follows:</p><pre><br> newcap := nextslicecap(newLen, oldCap)<br><br> var overflow bool<br> var lenmem, newlenmem, capmem uintptr<br> // Specialize for common values of et.Size.<br> // For 1 we don&#39;t need any division/multiplication.<br> // For goarch.PtrSize, compiler will optimize division/multiplication into a shift by a constant.<br> // For powers of 2, use a variable shift.<br> noscan := !et.Pointers()<br> switch {<br> case et.Size_ == 1:<br>  lenmem = uintptr(oldLen)<br>  newlenmem = uintptr(newLen)<br>  capmem = roundupsize(uintptr(newcap), noscan)<br>  overflow = uintptr(newcap) &gt; maxAlloc<br>  newcap = int(capmem)<br> case et.Size_ == goarch.PtrSize:<br>  lenmem = uintptr(oldLen) * goarch.PtrSize<br>  newlenmem = uintptr(newLen) * goarch.PtrSize<br>  capmem = roundupsize(uintptr(newcap)*goarch.PtrSize, noscan)<br>  overflow = uintptr(newcap) &gt; maxAlloc/goarch.PtrSize<br>  newcap = int(capmem / goarch.PtrSize)<br> case isPowerOfTwo(et.Size_):<br>  var shift uintptr<br>  if goarch.PtrSize == 8 {<br>   // Mask shift for better code generation.<br>   shift = uintptr(sys.TrailingZeros64(uint64(et.Size_))) &amp; 63<br>  } else {<br>   shift = uintptr(sys.TrailingZeros32(uint32(et.Size_))) &amp; 31<br>  }<br>  lenmem = uintptr(oldLen) &lt;&lt; shift<br>  newlenmem = uintptr(newLen) &lt;&lt; shift<br>  capmem = roundupsize(uintptr(newcap)&lt;&lt;shift, noscan)<br>  overflow = uintptr(newcap) &gt; (maxAlloc &gt;&gt; shift)<br>  newcap = int(capmem &gt;&gt; shift)<br>  capmem = uintptr(newcap) &lt;&lt; shift<br> default:<br>  lenmem = uintptr(oldLen) * et.Size_<br>  newlenmem = uintptr(newLen) * et.Size_<br>  capmem, overflow = math.MulUintptr(et.Size_, uintptr(newcap))<br>  capmem = roundupsize(capmem, noscan)<br>  newcap = int(capmem / et.Size_)<br>  capmem = uintptr(newcap) * et.Size_<br> }</pre><p>The implementation of et.Pointers at the top line is as follows. According to the comments, noscan is expected to be false for cases where the type is a basic data type, a struct that does not contain pointers, a struct where the first field is a pointer, or an empty struct. noscan is a variable related to memory alignment requirements.</p><pre>type Type struct {<br>  Size_ uintptr<br>  PtrBytes    uintptr <br>// number of (prefix) bytes in the type that can contain pointers<br>...<br>}<br>func (t *Type) Pointers() bool { return t.PtrBytes != 0 }</pre><p>In the case of et.Size_, which determines the important logic, it represents the size of the type. Specifically, it is the value returned by unsafe.Sizeof(element).</p><p>Let’s examine each case in detail.</p><h4><strong>et.Size_ == 1</strong></h4><p>When the data type size is 1 byte. This typically applies to types like byte.</p><ul><li><strong>lenmem</strong>: Memory size for the current length.</li><li><strong>newlenmem</strong>: Memory size for the new length.</li><li><strong>capmem</strong>: Memory size aligned to the new capacity. The roundupsize function is used.</li><li><strong>overflow</strong>: Checks if the new capacity exceeds maxAlloc.</li><li><strong>newcap</strong>: The new capacity derived from the aligned memory size.</li></ul><h4><strong>et.Size_ == goarch.PtrSize</strong></h4><p>When the data type size is equal to the pointer size (goarch.PtrSize). This applies to scenarios such as arrays of pointers.</p><ul><li><strong>lenmem and </strong><strong>newlenmem</strong>: Adjust the memory size based on the pointer size.</li><li><strong>capmem</strong>: Align the memory size to the new capacity, adjusted according to the pointer size.</li><li><strong>overflow</strong>: Check if the new capacity exceeds maxAlloc divided by the pointer size.</li><li><strong>newcap</strong>: Calculate the new capacity from the aligned memory size.</li></ul><h4><strong>isPowerOfTwo(et.Size_)</strong></h4><p>When the data type size is a power of 2. In this case, bitwise operations are used to efficiently calculate the memory size.</p><ul><li><strong>shift</strong>: When et.Size_ is a power of 2, bit shifting is used for efficient calculation.</li><li><strong>lenmem and </strong><strong>newlenmem</strong>: Adjust memory size using bit shifting.</li><li><strong>capmem</strong>: Align the memory size to the new capacity using bit shifting.</li><li><strong>overflow</strong>: Check if the new capacity exceeds maxAlloc divided by the shifted value.</li><li><strong>newcap</strong>: Calculate the new capacity from the aligned memory size.</li></ul><h4>default</h4><p>For cases that do not match the above conditions: Basic memory size adjustment is performed.</p><ul><li><strong>lenmem and </strong><strong>newlenmem</strong>: Adjust the memory size using the data type size.</li><li><strong>capmem</strong>: Calculate the memory size for the new capacity.</li><li><strong>overflow</strong>: Check for overflow by multiplying the data type size with the memory size.</li><li><strong>newcap</strong>: Calculate the new capacity from the aligned memory size.</li></ul><p>What is the roundupsize function that appears repeatedly?</p><h3>roundupsize</h3><p>This function is used in Go’s memory management system to align the size of memory blocks. It adjusts memory blocks to the appropriate size during allocation, enhancing memory usage efficiency and ensuring proper memory alignment. The function differentiates between small and large objects, calculating the appropriate memory size for each.</p><pre>func roundupsize(size uintptr, noscan bool) (reqSize uintptr) {<br> reqSize = size<br> if reqSize &lt;= maxSmallSize-mallocHeaderSize {<br>  // Small object.<br>  if !noscan &amp;&amp; reqSize &gt; minSizeForMallocHeader { // !noscan &amp;&amp; !heapBitsInSpan(reqSize)<br>   reqSize += mallocHeaderSize<br>  }<br>  // (reqSize - size) is either mallocHeaderSize or 0. We need to subtract mallocHeaderSize<br>  // from the result if we have one, since mallocgc will add it back in.<br>  if reqSize &lt;= smallSizeMax-8 {<br>   return uintptr(class_to_size[size_to_class8[divRoundUp(reqSize, smallSizeDiv)]]) - (reqSize - size)<br>  }<br>  return uintptr(class_to_size[size_to_class128[divRoundUp(reqSize-smallSizeMax, largeSizeDiv)]]) - (reqSize - size)<br> }<br> // Large object. Align reqSize up to the next page. Check for overflow.<br> reqSize += pageSize - 1<br> if reqSize &lt; size {<br>  return size<br> }<br> return reqSize &amp;^ (pageSize - 1)<br>}</pre><h4>reqSize &lt;= maxSmallSize - mallocHeaderSize)</h4><p>When the object is considered small</p><ul><li><strong>Small Objects</strong>: If the size is less than or equal to smallSizeMax - 8, return the aligned size using the class_to_size and size_to_class8 arrays.</li><li><strong>Larger Small Objects</strong>: If the size exceeds smallSizeMax, find the aligned size using the class_to_size and size_to_class128 arrays.</li></ul><h4>reqSize &gt; maxSmallSize — mallocHeaderSize</h4><ul><li><strong>Page Size Alignment</strong>: Align reqSize to the next page size boundary to ensure proper memory alignment. pageSize represents the size of a memory page.</li><li><strong>Overflow Check</strong>: If the size after page alignment is smaller than the original request size, return the original size.</li><li><strong>Return Aligned Size</strong>: Return the memory block size aligned to the page size.</li></ul><p>After all these operations are completed, we obtain the new slice!</p><h3>Conclusion</h3><p>In fact, even while writing this post, I couldn’t precisely determine what happens for each type. Explaining it verbally, especially while reviewing the code, would be quite challenging.</p><p>However, as a Gopher, it is satisfying to know that slices are not merely doubled but are returned with new capacities based on different calculations depending on their type.</p><p>With this knowledge, there will surely be opportunities to apply it in the future, won’t there?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46289dad4730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which function should you use to sort a slice?]]></title>
            <link>https://thekoreanguy.medium.com/which-function-should-you-use-to-sort-a-slice-faeb181f81af?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/faeb181f81af</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[heap-memory]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 13:07:15 GMT</pubDate>
            <atom:updated>2024-07-22T13:07:15.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I want to explore different ways to sort a integer slice in Go.</p><p>We will compare three functions: slices.Sort, slices.SortFunc, and sort.Slice.</p><p>First, let’s take a look at the benchmark results.</p><pre><br>func BenchmarkSortSlice(b *testing.B) {<br> b.ReportAllocs()<br> b.StopTimer()<br> arr := make([]int, 1000000)<br> for i := 0; i &lt; 1000000; i++ {<br>  arr[i] = rand.Intn(1000)<br> }<br> b.StartTimer()<br> for i := 0; i &lt; b.N; i++ {<br>  sort.Slice(arr, func(i, j int) bool {<br>   return arr[i] &lt; arr[j]<br>  })<br> }<br>}<br><br>func BenchmarkSlicesSortFunc(b *testing.B) {<br> b.ReportAllocs()<br> b.StopTimer()<br> arr := make([]int, 1000000)<br> for i := 0; i &lt; 1000000; i++ {<br>  arr[i] = rand.Intn(1000)<br> }<br> b.StartTimer()<br> for i := 0; i &lt; b.N; i++ {<br>  slices.SortFunc(arr, func(a, b int) int {<br>   return a - b<br>  })<br> }<br>}<br><br>func BenchmarkSlicesSort(b *testing.B) {<br> b.ReportAllocs()<br> b.StopTimer()<br> arr := make([]int, 1000000)<br> for i := 0; i &lt; 1000000; i++ {<br>  arr[i] = rand.Intn(1000)<br> }<br> b.StartTimer()<br> for i := 0; i &lt; b.N; i++ {<br>  slices.Sort(arr)<br> }<br>}<br><br>// cpu: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz<br>// BenchmarkSortSlice<br>// BenchmarkSortSlice-12               405    2796977 ns/op       56 B/op        2 allocs/op<br>// BenchmarkSlicesSortFunc<br>// BenchmarkSlicesSortFunc-12          535    2215764 ns/op        0 B/op        0 allocs/op<br>// BenchmarkSlicesSort<br>// BenchmarkSlicesSort-12             1105    1058691 ns/op        0 B/op        0 allocs/op      0 allocs/op</pre><p>As you can see, when sorting an integer slice, slices.Sort performs the best, followed by slices.SortFunc, and then sort.Slice.</p><p>All of these functions are included in Go’s standard packages, but why is there a difference in performance?</p><h3>sort.Slice vs slices.SortFunc</h3><p>First, let’s compare sort.Slice and slices.SortFunc, both of which allow sorting with a custom function.</p><pre>// sort.Slice<br>func Slice(x any, less func(i, j int) bool) {<br> rv := reflectlite.ValueOf(x)<br> swap := reflectlite.Swapper(x)<br> length := rv.Len()<br> limit := bits.Len(uint(length))<br> pdqsort_func(lessSwap{less, swap}, 0, length, limit)<br>}<br><br>// slices.SortFunc<br>func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {<br> n := len(x)<br> pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp)<br>}</pre><p>Both functions use the <a href="https://github.com/orlp/pdqsort">pdqsort algorithm</a>.</p><p>The difference is that sort.Slice uses the any keyword, while slices.SortFunc utilizes generics.</p><p>In my view, the only difference lies in reflectlite.ValueOf(x) and reflectlite.Swapper(x). It appears that these two methods internally call functions from the unsafe package, which may potentially lead to heap memory allocations. Allocating memory on the heap is a task with considerable overhead, which likely contributes to the observed performance degradation.</p><p>On the other hand, slices.SortFunc avoids this overhead because generics provide type safety, eliminating the need for such processes.</p><p>Functions that use generics are generated at compile time, so they don’t require reflection and thus avoid heap memory allocation. This results in better performance.</p><p>So, what is the difference between slices.SortFunc and slices.Sort?</p><pre>// slices.Sort<br>func Sort[S ~[]E, E cmp.Ordered](x S) {<br>  n := len(x)<br>  pdqsortOrdered(x, 0, n, bits.Len(uint(n)))<br>}<br><br>// cmd.Ordered<br>type Ordered interface {<br> ~int | ~int8 | ~int16 | ~int32 | ~int64 |<br>  ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |<br>  ~float32 | ~float64 |<br>  ~string<br>}<br><br>func Less[T Ordered](x, y T) bool {<br> return (isNaN(x) &amp;&amp; !isNaN(y)) || x &lt; y<br>}<br><br>func isNaN[T Ordered](x T) bool {<br> return x != x<br>}</pre><p>The algorithm used in slices.Sort is identical to the one in sort.Slice, and since it uses generics, no reflection occurs. Additionally, Ordered.Less is a predefined function used in slices.Sort, whereas slices.Sort accepts a function as an argument. Passing a function as an argument can introduce additional function call overhead, which may impact performance, especially when there are many comparison functions involved.</p><h3>Conclusion</h3><p>We have explored the three slice sorting functions provided by Go. In the past, only sort.Slice existed, which used Tim sort, though it wasn’t mentioned on this post. However, since 2022, Go has adopted pdqsort, a modern sorting algorithm that combines the fast average case performance of randomized quicksort with the efficient worst-case performance of heapsort, and achieves linear time for certain input patterns. This change improved performance, and subsequent versions, starting with Go 1.22, introduced slices.Sort and slices.SortFunc, further enhancing sorting performance.</p><p>Now, you can experience better sorting performance by using slices.Sort for sorting tasks, or slices.SortFunc when a custom comparison function is needed.</p><p>As Go continues to evolve, it is essential for us to keep an eye on these advancements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faeb181f81af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go errors.Is now includes a nil check.]]></title>
            <link>https://thekoreanguy.medium.com/go-errors-is-now-includes-a-nil-check-94f82fe4cc31?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/94f82fe4cc31</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[gopher]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[go-errors]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 12:50:21 GMT</pubDate>
            <atom:updated>2024-08-25T12:46:45.688Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>In Go 1.23, the addition of a nil check to errors.Is makes it easier to maintain the happy path when handling errors.</p><p>After the Go 1.23 freeze period, the go1.23rc tag has finally been released.</p><p>Here are the <a href="https://tip.golang.org/doc/go1.23">release notes</a>.</p><p>However, there is a section that I personally consider important, which is missing. It concerns the errors.Is .</p><p>Before Go 1.23, errors.Is did not check if the error being examined was nil. The code at that time was as <a href="https://github.com/golang/go/blob/go1.22.5/src/errors/wrap.go#L44-L51">follows</a>:</p><pre>func Is(err, target error) bool {<br> if target == nil {<br>  return err == target<br> }<br><br> isComparable := reflectlite.TypeOf(target).Comparable()<br> return is(err, target, isComparable)<br>}</pre><p>Therefore, to check if the error returned by a function was a specific error, you had to use nested if statements like this:</p><pre>err := foo()<br>if err != nil {<br>  if errors.Is(err, errorBar) {<br>    // handle error Bar<br>  }<br>  if errors.Is(err, errorBar2) {<br>    // handle error Bar2<br>  }<br>  // handle other errors<br>}</pre><p>While this code might not cause any issues, it is not particularly pretty.</p><p>With Go 1.23, you can now handle error checking with only a single level of depth, eliminating the need for nested if statements. This improvement is due to the <a href="https://github.com/golang/go/blob/go1.23rc1/src/errors/wrap.go#L44-L51">following code change</a>:</p><pre>func Is(err, target error) bool {<br> if err == nil || target == nil {<br>  return err == target<br> }<br><br> isComparable := reflectlite.TypeOf(target).Comparable()<br> return is(err, target, isComparable)<br>}</pre><p>Previously, the errors.Is only checked if the target error (i.e., the predefined error) was nil. However, now it also checks if the actual error returned is nil.</p><p>As a result, we can improve the code as follows:</p><pre>err := foo()<br>if errors.Is(err, errorBar) {<br>  // handle error Bar<br>}<br>if errors.Is(err, errorBar2) {<br>  // handle error Bar2<br>}<br>if err != nil {<br>  // handle other errors<br>}</pre><p>I believe this approach is better than the previous code. Although it might seem like a small change, it significantly improves readability and reduces complexity compared to the old one.</p><p>The previous code, with its nested if statements, can be more confusing and complex to read later on, despite appearing straightforward when initially written.</p><p>When writing code, it’s essential to handle other errors, but there’s also a risk of missing non-exception errors while managing exceptions.</p><p>Code without unnecessary depth like this is defined as satisfying the <strong><em>HAPPY PATH.</em></strong></p><p>In the book <a href="https://100go.co/"><em>100 Go Mistakes and How to Avoid Them</em></a>, the author states: “Avoiding nested levels and keeping the happy path aligned on the left makes building a mental code model easier.” And I completely agree with that.</p><p>Therefore, in the future, let’s make sure to follow the happy path approach as shown when handling errors.</p><h3><strong>Conclusion</strong></h3><p>When errors.Is did not have a nil check, I encountered numerous mistakes and difficulties in reading code, and I was quite dissatisfied with the lack of a nil check in errors.Is.</p><p>However, now that it has been introduced, and despite the philosophical disagreements some Gophers might have, this enhancement will significantly aid in writing code that maintains the happy path, improving readability and reducing complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94f82fe4cc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go 1.22 slices.Concat]]></title>
            <link>https://thekoreanguy.medium.com/go-1-22-slices-concat-b15b8e762b98?source=rss-f72b2d8b11bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b15b8e762b98</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[the korean guy]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 13:08:07 GMT</pubDate>
            <atom:updated>2024-07-30T11:32:12.102Z</atom:updated>
            <content:encoded><![CDATA[<p>I was going through slices.Concat and came across a part that I didn’t understand, so I tried summarizing it.</p><p><strong><em>As I’m still a beginner, there might be some inaccuracies. If you notice any such issues, please feel free to let me know.</em></strong></p><h3><strong>Summary</strong></h3><ol><li>The input size to slices.Grow is the ‘MINIMUM’ capacity returned by the slice.</li><li>After calling the slices.Concat, you can perform appends with minimal overhead.</li><li>However, it’s unclear how effective this is.</li></ol><p>slices.Concat<strong><em> </em></strong>is a function released in Go version 1.22 that can merge multiple slices into one.</p><p>The implementation of this function is as follows:</p><pre>func Concat[S ~[]E, E any](slices ...S) S {<br>    size := 0<br>    for _, s := range slices {<br>        size += len(s)<br>        if size &lt; 0 {<br>            panic(&quot;len out of range&quot;)<br>        }<br>    }<br>    newslice := Grow[S](nil, size)<br>    for _, s := range slices {<br>        newslice = append(newslice, s...)<br>    }<br>    return newslice<br>}</pre><p>The part I don’t quite understand is newslice := Grow[S](nil, size).</p><h4>Reason why I couldn’t understand</h4><ol><li><em>a slice with a capacity different from the requested parameter size is returned.</em></li><li><em>built-in </em><em>make is faster than </em><em>slices.Grow</em></li><li><em>I think built-in </em><em>make is more readable.</em></li></ol><p>So I found the slices.Grow implementation, and the part that determines the <strong>capacity</strong> of the slice is as follows:</p><pre>s = append(s[:cap(s)], make([]E, n)...)[:len(s)]</pre><p>Assuming you call slices.Concat([]int{1,2,3}, []int{4,5,6}), it can be replaced as follows:</p><pre>s = append([]int{}, make([]int, 6)...)[:0]</pre><p>The above code is a part of the slices.Grow implementation, and using make(S, size) instead of slices.Grow[S](nil, size) in slices.Concat would naturally be faster.</p><p>Although it seemed counterintuitive, I ran a benchmark to confirm it.</p><pre>// use slices.Grow <br>func BenchmarkSlicesGrow(b *testing.B) {<br>    b.ReportAllocs()<br>    for i := 0; i &lt; b.N; i++ {<br>        _ = slices.Grow[[]int](nil, size)<br>    }<br>}<br>// use built-in make<br>func BenchmarkMake(b *testing.B) {<br>    b.ReportAllocs()<br>    for i := 0; i &lt; b.N; i++ {<br>        _ = make([]int, 0, size)<br>    }<br>}<br><br>//BenchmarkSlicesGrow-10  304332          3683 ns/op       81920 B/op           1 allocs/op<br>//BenchmarkMake-10        390796          2873 ns/op       81920 B/op           1 allocs/op</pre><p>As expected, make was faster.</p><p>So curious about the author’s intent, I checked <a href="https://go-review.googlesource.com/c/go/+/504882/3..6/src/slices/slices.go#b510">Gerrit</a> and found that the original code used make, and it was changed to Grow in the review below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTDoQnybY-dmMRf1PHudJg.png" /></figure><p>However, I couldn’t understand the review comments, as the fact that slices.Grow does not guarantee capacity is a <em>result of the change to </em><em>slices.Grow</em>, and thus it <em>couldn&#39;t be the reason for the change</em>.</p><p>So, I left a question, and the response I received is as follows:</p><pre>s := slices.Concat(s1,s2)<br>s = append(s, 7)</pre><p>It seems that the intent was to account for additional capacity for new elements being added to the slice after using the slices.Concat function.</p><p>But, it’s unclear how often this use case occurs. I wondered if using make instead of slices.Grow in slices.Concat, and using slices.Concat instead of append, would resolve the issue. So I ran the following benchmark:</p><pre>func Concat[S ~[]E, E any](slices ...S) S {<br> size := 0<br> for _, s := range slices {<br>  size += len(s)<br>  if size &lt; 0 {<br>   panic(&quot;len out of range&quot;)<br>  }<br> }<br> newslice := make(S, 0, size)<br> for _, s := range slices {<br>  newslice = append(newslice, s...)<br> }<br> return newslice<br>}<br><br>func BenchmarkConcatAndAppend(b *testing.B) {<br> b.ReportAllocs()<br> for i := 0; i &lt; b.N; i++ {<br>  _ = append(append(slices.Concat(make([]int, i), make([]int, i)), make([]int, i)...), make([]int, i)...)<br> }<br>}<br><br>func BenchmarkCustomConcat(b *testing.B) {<br> b.ReportAllocs()<br> for i := 0; i &lt; b.N; i++ {<br>  _ = Concat(make([]int, i), make([]int, i), make([]int, i), make([]int, i))<br> }<br>}<br><br>// cpu: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz<br>// BenchmarkConcatAndAppend<br>// BenchmarkConcatAndAppend-12        16224     142381 ns/op   759526 B/op        4 allocs/op<br>// BenchmarkCustomConcat<br>// BenchmarkCustomConcat-12           19066     116000 ns/op   627808 B/op        5 allocs/op</pre><p>As you see, using make to concatenate multiple slices at once is more performance-efficient.</p><h4>Conclusion</h4><p>Although I don’t fully understand it yet, the developer of slices.Concat suggests that using slices.Grow instead of make is a way to reduce overhead when append occur later.</p><p>Of course, since a dynamic slice copies and increases its size when the capacity is exceeded during append, this might be the reason.</p><p>However, such cases might be resolved by using Concat with three or more slices instead of append. It seems like there might be something I&#39;m still missing. Next, I plan to examine the root cause of this curiosity: <a href="https://medium.com/@ojh031/how-does-the-capacity-change-when-you-append-to-a-slice-in-go-46289dad4730">append</a>.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b15b8e762b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>