<?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 Val Deleplace on Medium]]></title>
        <description><![CDATA[Stories by Val Deleplace on Medium]]></description>
        <link>https://medium.com/@val_deleplace?source=rss-5c7fb9360a28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*gAPjqYvkdSTGHBaHzU53uA.jpeg</url>
            <title>Stories by Val Deleplace on Medium</title>
            <link>https://medium.com/@val_deleplace?source=rss-5c7fb9360a28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:22:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@val_deleplace/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[Voice AI: Deconstructing the Cascaded Pipeline]]></title>
            <link>https://medium.com/@val_deleplace/voice-ai-deconstructing-the-cascaded-pipeline-10ac93a4855b?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ac93a4855b</guid>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[gemini-api]]></category>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[speech-to-text-app]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 16:03:52 GMT</pubDate>
            <atom:updated>2026-11-25T16:41:44.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bu_aY-AKxu6rXCeCrNtaSQ.png" /></figure><h3>1. The Anatomy of a Chained Voice Stack</h3><p>Before the rise of native multimodal models, conversational voice systems relied on a chained “cascaded” pipeline stitching together three distinct subsystems across separate network boundaries and protocols (ranging from HTTP/REST endpoints and gRPC calls to intermediate WebSocket connections):</p><p>1. Speech-to-Text (STT) for acoustic transcription.</p><p>2. A text-based reasoning engine, ranging from early NLU/intent-matching systems like classic Siri and Google Assistant to modern text LLMs.</p><p>3. Text-to-Speech (TTS) for voice synthesis.</p><p>While conceptually modular, this design suffers from compounding latency, catastrophic acoustic information loss, and a fundamentally broken half-duplex interaction model.</p><h3>2. The Four Compounding Failure Modes</h3><h4>Failure Mode 1: Speech-to-Text (STT) &amp; Voice Activity Detection (VAD) Timers</h4><p>Audio is captured on the client, buffered, and streamed to an external transcription service. A rigid VAD timer must decide when the user has finished speaking. If the timeout is configured too aggressively (e.g., 400ms), users get cut off whenever they pause to think. If configured conservatively (e.g., 1,200ms), every single conversational turn suffers mandatory dead air before processing even begins.</p><h4>Failure Mode 2: Information Oblivion at the Text Boundary</h4><p>When speech is converted into plain UTF-8 text tokens, the entire acoustic dimension is permanently erased. Sarcasm, urgency, hesitation, laughter, volume modulations, whispers, and emotional coloring disappear. The intermediate reasoning engine receives flat text strings, leaving it blind to how something was said.</p><h4>Failure Mode 3: Compounding Network Latency &amp; Serialization Overheads</h4><p>As the reasoning engine generates text, chunks are dispatched across another network hop to a separate TTS engine. Each transition across service boundaries incurs network transport overhead, Time-to-First-Token (TTFT), serialization, and buffering delays. Even with sentence-level streaming optimizations, serial network hops and buffering push compounded end-to-end latency to between 2,000ms and 4,500ms.</p><h4>Failure Mode 4: The Half-Duplex Operational Bottleneck</h4><p>The traditional stack is fundamentally half-duplex: the system is either listening or speaking, never both. If a user interjects while the bot is speaking, either the client must flush its playback buffer and send an out-of-band cancellation signal, or the bot talks over the user.</p><p>In the next article, we will examine the native audio-to-audio architecture that replaces this fragile cascade with a single, stateful bidirectional connection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ac93a4855b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Voice AI: The End of the Walkie-Talkie Era]]></title>
            <link>https://medium.com/@val_deleplace/voice-ai-the-end-of-the-walkie-talkie-era-9419a6cc203b?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/9419a6cc203b</guid>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[gemini-api]]></category>
            <category><![CDATA[speech-to-text-app]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 17:31:00 GMT</pubDate>
            <atom:updated>2026-11-24T15:43:33.288Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, interacting with a voice assistant felt less like having a natural conversation and more like communicating over a half-duplex walkie-talkie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XVlPRHodgBb53SzPGlV7A.png" /></figure><p>A user spoke into their microphone, paused, and then waited through two to four seconds of dead air while a cascade of disjointed systems processed the speech. Once the synthesized reply finally began playing, the user could not easily interrupt without awkward lag or completely breaking the conversation flow.</p><p>Even for basic utility bots, such as setting an alarm or querying flight status, that multi-second lag was already a painful and jarring friction that users only tolerated for lack of an alternative. But for high-tempo, dynamic applications such as real-time gaming, language tutoring, and live customer troubleshooting — such delays are utterly fatal. In these interactive contexts, conversational flow relies on micro-pauses, intonation, simultaneous backchannel listening, and instant interjections.</p><p>To be sure, speech-to-text software has been commercially available for decades. Specialized professions — most notably radiologists, pathologists, and attorneys — have long relied on dictation tools to streamline medical and legal workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNzQMNxzbD-h1Jr7YMvpVA.png" /><figcaption>One-way speech-to-text in clinical practice.</figcaption></figure><p>Yet across those decades, true two-way conversational voice never caught on for anyone, whether professionals or the general public. Between frustrating word error rates, rigid vocal ergonomics, and the unnatural friction of turn-taking delay, voice remained trapped as a cumbersome, one-way input method rather than a natural collaborative medium. It is this long-standing status quo that is now ready to change dramatically.</p><p>Late 2025, the artificial intelligence landscape <strong>crossed a monumental threshold</strong>: the transition from traditional cascaded pipelines (Speech-to-Text → Text LLM → Text-to-Speech) to native full-duplex audio-to-audio models. By handling raw audio natively in a unified neural network, platforms like the <a href="https://aistudio.google.com/docs/live-api">Gemini Live API</a> have brought conversational latency down into the human perceptual range (under 300 milliseconds), unlocking a new frontier in cloud application development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Bd-IuOgmDRmSJulc5zj8Q.png" /><figcaption>A full-duplex voice conversation</figcaption></figure><p>In this series, we’ll explore how <strong>native live-audio streaming</strong> fundamentally changes application architecture — and how to build software that can listen, think, and speak at human speed. Stay tuned as we roll out the next installments in the days ahead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9419a6cc203b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When <= ≡ =>]]></title>
            <link>https://medium.com/@val_deleplace/when-fe60efe9bc2e?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe60efe9bc2e</guid>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 13:00:42 GMT</pubDate>
            <atom:updated>2026-08-22T13:00:42.004Z</atom:updated>
            <content:encoded><![CDATA[<p>This one was for me the most disturbing realization about boolean operators.</p><h3>1. Comparable booleans</h3><p>For better or for worse, programming languages like Python, C++, JavaScript, PHP, Rust support comparing boolean values with the <strong>&lt;=</strong> operator. For all of them, <em>false</em> <strong>&lt;</strong> <em>true</em>.</p><p>Here is the truth table for the expression <strong>a &lt;= b</strong> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc89239296f8773d15c70fa367b0d2f/href">https://medium.com/media/4cc89239296f8773d15c70fa367b0d2f/href</a></iframe><h3>2. Implication</h3><p>Though less common in programming, the <strong>implies</strong> operator <strong>=&gt;</strong> is defined as : ( <strong>a =&gt; b</strong> ) is true IFF ( <strong>¬a ∨ b</strong> ) is true.</p><p>Informally, <strong>a =&gt; b</strong> gives you valuable information about <strong>b</strong> when <strong>a</strong> is true, and no information when <strong>a</strong> is false.</p><p>Here is the truth table for “<strong>a </strong>implies <strong>b</strong>” :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc732e39ee4c8063a1787f26b92a85fb/href">https://medium.com/media/dc732e39ee4c8063a1787f26b92a85fb/href</a></iframe><h3>Conclusion</h3><p>The two truth tables are identical. The two operators have the same semantics (only on booleans), even though they look symmetric.</p><p>This should mean that <strong>a&lt;=b</strong> is equal to <strong>a=&gt;b</strong>, fortunately there exists no programming language that supports both operators. That would be confusing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe60efe9bc2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration of cloud components of Cool Maze - Push to Computer]]></title>
            <link>https://medium.com/google-cloud/migration-of-cloud-components-of-cool-maze-push-to-computer-3bda2b3d244e?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bda2b3d244e</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-storage]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 12:19:21 GMT</pubDate>
            <atom:updated>2025-11-21T00:47:44.833Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://coolmaze.io/">Cool Maze - Push to Computer</a> is a mobile app that lets you send a photo from your mobile to your computer, by scanning a QR code. We’ve described its cloud architecture in <a href="https://medium.com/google-cloud/the-cloud-architecture-of-cool-maze-f6739e7fea03">this previous article</a>.</p><p>We sometimes replace components to modernize the system, improve performance, and optimize costs. Here are a few “bricks” we’ve migrated.</p><h3>Application server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lIAwsSqvV9F39Q9N.png" /></figure><p>The backend was originally hosted on <a href="https://cloud.google.com/appengine">Google App Engine</a>, a fantastic managed application server supporting the <a href="https://go.dev/">Go</a> language.</p><p>We migrated to <a href="https://cloud.google.com/run">Cloud Run</a>, which is even more powerful as it allows the deployment of arbitrary Docker containers.</p><p>App Engine and Cloud Run both rely on <a href="https://docs.cloud.google.com/run/docs/about-instance-autoscaling">autoscaling</a>, meaning server instances are automatically started or shut down as incoming traffic increases or decreases. For this architecture, it is crucial to design <em>stateless</em> instances: each instance must be able to process any incoming request without relying on local data. Instead, stateful data must be stored in a distributed memory component, or in a database.</p><h3>Transient memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q2cQnrNRFjW5oMNi.png" /></figure><p>Cool Maze — Push to Computer writes and reads short-lived action data, such as “a web page is currently displaying a QR code and waiting for updates on channel <em>C</em>”.</p><p>App Engine included the built-in distributed memory system <a href="https://docs.cloud.google.com/appengine/docs/standard/services/memcache?tab=go">Memcache</a>.</p><p>For Cloud Run, the closest equivalent would be <a href="https://cloud.google.com/memorystore">Cloud Memorystore</a>, which has a significant drawback: the <a href="https://cloud.google.com/memorystore/docs/redis/pricing">cost</a> of deploying and maintaining a running instance.</p><p>Instead, we switched to a hybrid approach involving Cloud Run in-memory data and Cloud Firestore.</p><ul><li>Cool Maze — Push to Computer usually requires a single Cloud Run instance. Thus, it is technically possible to keep an in-memory cache of data directly in the server’s memory. When information is already in the cache, reads are extremely fast. However, instances may be shut down at any time, so we cannot rely solely on server memory.</li><li>We also write the short-lived data to <a href="https://cloud.google.com/products/firestore">Cloud Firestore</a>. Reading from Firestore is less performant than from in-memory options, but the latency remains acceptable and is only needed as a fallback when the information is not found in the memory cache.</li></ul><p>This strategy is only correct because our flow does not overwrite values and therefore does not cause any conflict between the state of the local memory and the state in Firestore.</p><h3>File server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*STH1csTtKS5TDnvs.png" /></figure><p>The primary file server for encrypted payloads in transit is <a href="https://cloud.google.com/storage">Google Cloud Storage</a>. If the payload is small enough, the Cool Maze — Push to Computer Android app is optimized to upload directly to Cloud Run, saving HTTPS requests.</p><h3>Server push</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cy9kJ2IfZjrOHIC6.png" /></figure><p>The flow of sharing a photo via Cool Maze — Push to Computer requires the backend to notify the web page as soon as the data becomes available: first the lightweight preview, then the full picture.</p><p>We originally used the service <a href="https://pusher.com/">Pusher.com</a> to achieve this. While very reliable and performant, this service has a non-negligible cost when exceeding the initial free tier.</p><p>We switched to Cloud Firestore’s <a href="https://firebase.google.com/docs/firestore/query-data/listen">realtime updates</a> feature. Firestore is a database, which is fundamentally different from a live messaging system. However, the realtime updates capability effectively lets the server notify clients when certain events occur, such as the modification of a document. We reimplemented server push over Firestore as follows:</p><ul><li>When the web page displays the QR code, it starts “listening” for updates to a specific, one-off Firestore document.</li><li>When the mobile device sends data to the server, the server writes event information to the Firestore document. The web page immediately receives the update.</li></ul><p>Cloud Firestore has a generous <a href="https://docs.cloud.google.com/free/docs/free-cloud-features#firestore">free tier</a>, as well as attractive <a href="https://cloud.google.com/firestore/pricing">pricing</a>.</p><h3>Analytics database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wBqaQZeLwwcRkvLf.png" /></figure><p>The system uses a database in “write-only” mode to append facts such as “a user shared one file of size 190 kB at 9:25 am”. This data later enables powerful analysis of traffic and service quality.</p><p>We originally stored this logging data in a <a href="https://docs.cloud.google.com/sql/docs/introduction">Cloud SQL</a> database. This approach had two drawbacks:</p><ul><li>As the volume of data increased, the performance of complex SQL aggregate queries tended to deteriorate. Some could be improved by adding yet another index, but interactive querying in general was becoming slower each month.</li><li>Cloud SQL is not “serverless”: the MySQL VM instance was running continuously, accounting for up to 80% of total cloud costs.</li></ul><p>We solved both concerns by replacing Cloud SQL with <a href="https://cloud.google.com/bigquery">BigQuery</a>. BigQuery consistently handles heavy analytics SQL queries in about five seconds, requires no instance management, and has a generous <a href="https://docs.cloud.google.com/free/docs/free-cloud-features#bigquery">free tier</a>.</p><p><em>This article was cross-posted from </em><a href="https://blog.coolmaze.io/posts/019-migrations/"><em>The Cool Maze - Push to Computer</em></a><em> blog.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bda2b3d244e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/migration-of-cloud-components-of-cool-maze-push-to-computer-3bda2b3d244e">Migration of cloud components of Cool Maze - Push to Computer</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Puzzle: Gemini CLI Tells Me Why My “Faster” Code Wasn’t]]></title>
            <link>https://medium.com/@val_deleplace/performance-puzzle-gemini-cli-tells-me-why-my-faster-code-wasnt-72ab12f16feb?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/72ab12f16feb</guid>
            <category><![CDATA[gemini-cli]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 14:22:06 GMT</pubDate>
            <atom:updated>2025-09-19T14:22:06.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I had a fantastic conversation with <a href="https://github.com/google-gemini/gemini-cli">Gemini CLI</a>, in just five prompts, when working on <a href="https://github.com/Deleplace/microbenchmarks/blob/master/bound_checks/bce_test.go#L92">a Go benchmark</a>.</p><ul><li>Show me the go assembly code generated for max4C and max4D</li><li>max4D produces fewer (50) lines of assembly than max4C (66). How would you explain the difference?</li><li>Thank you. Which ones are the assembly lines doing the bound checks?</li><li>Why do you think the two functions have the same performance, according to my benchmark results?</li><li>This was an excellent conversation. Could you relate it in an engaging technical blog post?</li></ul><p>The answers to the first four prompts were so great, that I asked for a story. Here is what the model wrote :)</p><p>As developers, we love to optimize. We rearrange loops, choose algorithms with better complexity, and fine-tune data access patterns, all in the pursuit of speed. But sometimes, the compiler and the CPU have a surprise for us. You can craft what seems like a more optimal piece of code, only for a benchmark to tell you <strong>it makes no difference</strong>.</p><p>This is a story about one such puzzle. A story of two seemingly identical functions, a clever compiler optimization, and a microbenchmark that sent us on a wild goose chase.</p><p><strong>The Contenders: Two Functions Enter, One Should Win</strong></p><p>Let’s say we want to find the maximum value in a tiny slice of four uint64 values. We might write a few different versions. Consider these two:</p><p><strong>max4C:</strong> A straightforward approach, checking elements in order.</p><pre><br>func max4C(x []uint64) uint64 {<br>    max := x[0]<br>    if x[1] &gt; max {<br>        max = x[1]<br>    }<br>    if x[2] &gt; max {<br>        max = x[2]<br>    }<br>    if x[3] &gt; max {<br>        max = x[3]<br>    }<br>    return max<br>}</pre><p><strong>max4D:</strong> A slightly different version that starts from the end.</p><pre>func max4D(x []uint64) uint64 {<br>    max := x[3]<br>    if x[0] &gt; max {<br>        max = x[0]<br>    }<br>    if x[1] &gt; max {<br>        max = x[1]<br>    }<br>    if x[2] &gt; max {<br>        max = x[2]<br>    }<br>    return max<br>}</pre><p>Why? If <em>max4D</em> is doing less work, how can it be just as fast?</p><p><strong>The Real Culprit: We Weren’t Timing the Race</strong></p><p>The mystery isn’t in the functions themselves, but in how the benchmark calls them. The answer lies in this single expression, executed millions of times in a loop:</p><pre>data[j : j+4]</pre><p>This is a slicing operation. It doesn’t pass a piece of the original data slice directly. Instead, it creates a <strong>new slice header</strong> on every single iteration. This header — a pointer, a length, and a capacity — is what gets passed to our functions.</p><p>This has two profound effects:</p><p>1. <strong>The Slicing Overhead Dominates:</strong> Creating millions of these slice headers is not free. This overhead is the “heavy lifting” in our benchmark loop. It’s like timing two sprinters but spending 99% of the time driving them to the track. The small difference in their sprint times gets lost in the noise of the commute. The cost of the extra checks in <em>max4C</em> is completely dwarfed by the identical slicing cost in both benchmarks.</p><p>2. <strong>Perfectly Predictable Branches:</strong> The new slice created by data[j : j+4] is <em>always</em> exactly 4 elements long. When max4C runs its four bounds checks, the condition (len &lt;= index) is always false. Modern CPUs are phenomenal at <strong>branch prediction</strong>. They quickly learn that these checks will always pass and the “panic” branch will never be taken. A correctly predicted branch is incredibly cheap, effectively neutralizing the cost of the extra instructions in <em>max4C</em>.</p><p><strong>The Takeaway</strong></p><p>This investigation leaves us with a few key lessons:</p><ul><li><strong>Compiler Optimizations Are Your Friend:</strong> Structuring your code to help the compiler can have a real impact. The “descending index” pattern in <em>max4D</em> is a great way to enable Bounds Check Elimination.</li><li><strong>Microbenchmarking Is Hard:</strong> Be mindful of what you are actually measuring. The cost of your test setup can easily obscure the results you’re looking for.</li><li><strong>Modern Hardware Is Incredibly Smart:</strong> Don’t underestimate the power of features like branch prediction, which can make seemingly “slower” code run much faster than you’d expect.</li></ul><p>So, the next time you see a puzzling performance result, remember our story. The bottleneck might not be where you think it is. Dig a little deeper, look at the assembly, and question your assumptions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72ab12f16feb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe coding my scientific experiment]]></title>
            <link>https://medium.com/google-cloud/vibe-coding-my-scientific-experiment-dc143b20e3fd?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc143b20e3fd</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 09:42:28 GMT</pubDate>
            <atom:updated>2025-08-30T02:52:17.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuLMcRuZntaruZ80BRKg7A.png" /></figure><p>I have a mantra when it comes to generating QR codes: <strong>Make the payload small</strong>. Then, <strong>make it smaller</strong>.</p><p>The common sense about QR codes tells us the more information we encode into a QR code, the more black and white square modules are needed, the smaller the modules, and the more difficult it becomes to focus and scan using a mobile device. We prefer scanning to be <strong>fast and easy</strong>.</p><p>For example, one of these 2 QR codes is easier to scan. I’m letting you guess which one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/0*Fsxovkj34epwxi07.png" /><figcaption>“Hello, World”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*RC1V3PDpFpnIViVS.png" /><figcaption>“It is a truth universally acknowledged, that a single man in possession of a good fortune must be in want of a wife. However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered as the rightful property of some one or other of their daughters.”</figcaption></figure><p>Thus, encoding less information tends to improve the user experience. The scanning action has more chances to succeed, and succeeds faster. For example, using a URL shortener before generating a QR code leads to a friendlier, less complex, more performant QR code.</p><p>This is all intuitively true, but I wanted to go further and <strong>quantify</strong> this phenomenon. For this, I needed a realistic setup, a full-stack software platform, and a scientific protocol.</p><h4>Experimental setup</h4><p>This is my desired setup to collect measurements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-xNOou8jPLCOYrv3of0MQ.png" /></figure><p>A QR code is generated by a backend and displayed on a computer screen. A mobile device is scanning it. The mobile notifies the backend, which saves the measurements in a database and tells the computer to generate a new QR code. Rinse and repeat.</p><p>The code necessary to generate and scan QR codes using popular libraries is not very complex per se. However, writing it by hand would have taken me several days. The cost of writing boilerplaty code for 3 components (mobile app, web backend, web frontend) was high enough to deter me from building the experiment altogether.</p><h4>Vibe coding!</h4><p>But now is 2025 and AI assisted coding is a real thing. My experiment will come to life, mostly written by Gemini.</p><p>Integrating AI-generated code in a production system comes with real challenges. But for <strong>prototyping</strong> or <strong>building a throwaway experimental platform</strong>, vibe coding is just amazing.</p><p>I asked:</p><ul><li><a href="https://firebase.studio/">Firebase Studio</a> to generate a web frontend, connected to a Cloud Firestore database,</li><li><a href="http://goo.gle/4oZzFlc">Android Studio with Gemini</a> to generate a mobile app,</li><li><a href="http://goo.gle/4lQT45d">Gemini</a> to write <a href="http://goo.gle/4oZzK8u">Cloud Run functions</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8n8RCxFd06FfIZwxD7Blw.png" /></figure><p>The first results were very good. Within a few hours of guided work, I was ready to run the experiment and collect metrics in the database.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWu3b0hVwWLU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWu3b0hVwWLU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWu3b0hVwWLU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc66a4cb49fa5ed5d3a71937a59c0468/href">https://medium.com/media/bc66a4cb49fa5ed5d3a71937a59c0468/href</a></iframe><p>Each QR code is generated with a text payload having a random length, a random Error Correction Level (ECL) <strong><em>L</em></strong>, <strong><em>M</em></strong>, <strong><em>Q</em></strong>, or <strong><em>H</em></strong>, and has a random display size and a random position on screen.</p><p>The mobile device I’m using is not moving, but the QR code is moving towards the center of the screen, then stays fixed until scanned, or abandoned after a timeout of 7 seconds.</p><p>I gathered 5,000 data points in Firestore and exported them to BigQuery for analytics. The results surprised me!</p><blockquote>Hey, do you already know about these very nice BigQuery features?<br>- <a href="http://goo.gle/4n9ZHAQ">Pipe syntax</a><br>- <a href="http://goo.gle/3UR5xe8">Chart panel</a></blockquote><h3>Results</h3><h4>Display size matters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MG8JwihtiAmWO0XElIzNNg.png" /></figure><p>First, the size of the QR code matters a lot. At 50 x 50 pixels (too small), the scan almost always fails. At 600 x 600 pixels, the scan almost always succeeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*3xCxi67sALDDgi5Y6Sdb6w.png" /><figcaption>QR code too small (always fails)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*9gYEWrsIxpS-qvmVjz3JqQ.png" /><figcaption>QR code too large (always succeeds)</figcaption></figure><p>This chart teaches us the most “interesting” range of sizes is between 100 x 100 and 300 x 300. The subsequent queries will control for the size variable, removing the noise from QR codes too small or too large:</p><pre>|&gt; WHERE qrSize BETWEEN 100 AND 300</pre><h4>Payload size matters, but…</h4><p>The contents encoded in the QR code is a random alphanumerical string of random length, up to 50 characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmWkP84AI9naf7PX61599g.png" /></figure><p>It is expected, and observed, that a larger payload leads to more failures of detection. A string of length 50 has a 40% chance of failing to be scanned, with my specific experimental setup.</p><p>However, while the tendency is clear, I still need to take into account other factors that influence the detection:</p><ul><li>The Error Correction Level (ECL)</li><li>The QR code version, i.e. the number of modules in the grid</li></ul><h4>Error Correction Level matters</h4><p>A higher level of error correction helps scanning a QR code that is partially damaged, or partially hidden. This is achieved by encoding more bits of redundancy.</p><p>But should we expect a high level to <em>facilitate</em> scanning in the general case, or to <em>impede</em> it? On the one hand, more redundancy could mean higher chances for the scanner to detect “enough info”. On the other hand, more bits encoded may come with more modules, a higher QR code version, hence smaller modules, more difficult to detect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMJVhW_XeoSwm7qcbgatnA.png" /></figure><p>In my setup, higher levels (<strong><em>Q</em></strong>, <strong><em>H</em></strong>) tend to be less successful than lower levels (<strong><em>L</em></strong>, <strong><em>M</em></strong>) for any given payload size.</p><p>ECL is a parameter that we choose when generating the QR code. A high level makes sense for printing, because the paper QR code may become damaged over time. But for a QR code displayed on a computer screen, fully visible and undamaged, the lowest level <strong><em>L</em></strong> is preferable, as it encodes fewer bits of information.</p><h4>QR code Version matters, but…</h4><p>The <em>version</em> of a QR code represents the resolution of the grid:</p><ul><li>Version 1 for 21 x 21 modules (e.g. the first simple QR code at the top)</li><li>Version 13 for 69 x 69 modules (e.g. the complex QR code at the top)</li><li>Up to Version 40 for 177 x 177 modules</li></ul><p>For a fixed display size, a higher version has more modules, and each square module appears smaller.</p><p>Are higher versions more difficult to scan?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyTXBVufTW4_oeoezVvw7A.png" /></figure><p>Obviously, <em>yes</em>, but this chart is a bit misleading.</p><p>The version is usually not a user-defined setting at generation. Instead, the QR encoding library computes the <em>lowest version possible</em> that can fit the payload, with the chosen ECL. The real question is: for a chosen payload and a chosen ECL, which version is best for scanning?</p><p>When controlling for the payload size and the ECL, my data shows a slight advantage for the lowest version possible. In fact, the libraries are already taking the best decision by default.</p><h4>What about speed?</h4><p>The surprising result in the data I collected is that <em>I could not demonstrate any effect of the randomized parameters on the speed of detection</em>, when detection does happen.</p><p>In my setup, either the QR code was detected <strong>very fast</strong>, or it was <strong>not detected at all</strong> within 10 seconds. I conjecture this is because the distance between mobile and computer screen was fixed, and the display size of any given QR code was also fixed.</p><p>The real scan action by a human is a bit different: the user is aiming and closing in on the QR code until properly framed, at a suitable distance. Thus, it is still sensible to say that a less complex QR code, encoding less data, will be easier and faster to scan by a real user, at a suboptimal distance.</p><p>To properly demonstrate this, I would need to run the full experiment again with a twist: each QR code would start small and grow every second until detected or abandoned.</p><h4>QR code takeaways</h4><ul><li><strong>Yes</strong>, encoding smaller information facilitates scanning and fosters better UX</li><li>You do not need to set an explicit QR code version. Let the library decide.</li><li>If you display on a screen, choose the lowest error correction <strong><em>L</em></strong>.</li><li>More QR code technical details on the <a href="http://bit.ly/4lQQex5">Push to Computer blog</a></li></ul><h4>Useful Google Cloud links</h4><ul><li>Data visualization with <a href="http://goo.gle/4oP74z4">BigQuery data canvas</a></li><li>Vibe coding with <a href="https://firebase.studio/">Firebase Studio</a></li><li>Vibe coding with <a href="http://goo.gle/41wh0Ui">Gemini in Android Studio</a></li><li>Server push capability via <a href="http://goo.gle/423oaPZ">Firestore realtime updates</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc143b20e3fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/vibe-coding-my-scientific-experiment-dc143b20e3fd">Vibe coding my scientific experiment</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove objects from an image]]></title>
            <link>https://medium.com/google-cloud/remove-objects-from-an-image-352b63594383?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/352b63594383</guid>
            <category><![CDATA[comics]]></category>
            <category><![CDATA[imagen]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[paradox]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 13:55:26 GMT</pubDate>
            <atom:updated>2025-07-10T14:33:05.329Z</atom:updated>
            <content:encoded><![CDATA[<p>To create my last comic strip, I needed variations of an AI-generated image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9r30WEICVu-oNPIP6rPbA.png" /></figure><p>The panels consist of the same scene, with more or fewer people in it. To obtain such variants, I could either :</p><ul><li>Ask for a <strong>layered</strong> image if the model supports it, and open it in GIMP.</li><li>Or ask for several cutout images of objects and integrate them myself. However, the result may lack proper lighting, shadows, and overall consistency.</li><li>Or generate a full-fledged picture, and then <strong>remove</strong> some of the objects.</li></ul><p>This is what I did to create the comic strip : I prompted for a full classroom with <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/image/overview">Imagen</a> in Google Cloud Vertex AI Media Studio, and then used <a href="https://goo.gle/inpaint-remove">inpainting</a> to remove some of the students.</p><p>My original prompt:</p><blockquote>A drawing of 9 young adult students seated in a classroom. We see their face. In the foreground, we see only part of the back of a female teacher. More than 50% of the image height is above the head of the students.</blockquote><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqCHZteFh4As19__XaKXRA.jpeg" /><figcaption>A nice generated picture</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FisjfHXsKYUU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DisjfHXsKYUU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FisjfHXsKYUU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e36851674daadd01f174524ab0a4432/href">https://medium.com/media/2e36851674daadd01f174524ab0a4432/href</a></iframe><p>After a few iterations of removing students, I was ready to assemble the panels and add speech bubbles in Google Drawings.</p><p>If you’re interested in fun paradoxes, see the <a href="https://en.wikipedia.org/wiki/Will_Rogers_phenomenon">Will Rogers phenomenon</a>, <a href="https://en.wikipedia.org/wiki/Simpson%27s_paradox">Simpson’s paradox</a> and <a href="https://en.wikipedia.org/wiki/The_Book_of_Why">The Book of Why</a>.</p><p>To know more about inpainting features, have a look at the <a href="https://goo.gle/imagen-edit-images">Edit images</a> overview.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=352b63594383" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/remove-objects-from-an-image-352b63594383">Remove objects from an image</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The cloud architecture of Cool Maze]]></title>
            <link>https://medium.com/google-cloud/the-cloud-architecture-of-cool-maze-f6739e7fea03?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6739e7fea03</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 12:39:36 GMT</pubDate>
            <atom:updated>2025-04-01T16:55:09.075Z</atom:updated>
            <content:encoded><![CDATA[<p>Cool Maze is a mobile app that lets you send a photo from your mobile to your computer, by scanning a QR code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpoPqMiGm23g%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpoPqMiGm23g&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpoPqMiGm23g%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e01c8f7c6ec0231b1a33a69f1e2a57/href">https://medium.com/media/26e01c8f7c6ec0231b1a33a69f1e2a57/href</a></iframe><p>The app uses cloud servers to transfer data from the mobile source to the target computer. It needs cloud components with these capabilities:</p><ul><li>a web server for the static assets (HTML, JS, CSS) of the website <a href="https://coolmaze.io/">coolmaze.io</a>,</li><li>a web backend to handle the logic of API calls from the websites and from the mobile apps,</li><li>transient storage for payloads of a few megabytes in transit,</li><li>a “server push” component able to initiate a message from the server to the target browser,</li><li>a database, for analytics purposes.</li></ul><p>Here is our stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTeMhFwYBY3E4TDLJBoUEA.png" /><figcaption>Visit the original <a href="https://blog.coolmaze.io/posts/006-cloud-architecture/">Cool Maze blog post</a> to view the dynamic schema</figcaption></figure><p>Some of the logic is handled by the clients. For example, the mobile apps are responsible for encrypting user data, while the web app frontend decrypts it. The server does not handle user data encryption at all. Our <a href="https://en.wikipedia.org/wiki/End-to-end_encryption">end-to-end encryption</a> system ensures that the server manages only opaque encrypted resources and never has access to the cleartext user data or to the secret encryption keys.</p><p>The role of the cloud servers is to enable the mobile app to upload resources, allow the web app to download resources, and store anonymous usage data for analytics.</p><p>Note that all of the Google Cloud products mentioned here have <a href="https://cloud.google.com/free/docs/free-cloud-features#free-tier-usage-limits">a generous free tier</a>, helping reduce the operational costs to the bare minimum. A frugal design and several optimizations also contribute to making the service fast and cost-efficient.</p><p>I’m hosting the website static assets on <a href="https://firebase.google.com/docs/hosting">Firebase Hosting</a>.</p><p>I’m hosting the dynamic backend server on <a href="https://cloud.google.com/run">Cloud Run</a>. The server is written in <a href="https://go.dev/">Go</a>. Cloud Run is a fantastic option for our stateless HTTP server, as it is a managed platform that automatically scales the number of instances needed to serve the traffic at any given time.</p><h3>Stateless?</h3><p>If the server has no state, then where is the user data stored during transit? In this context, stateless means that the server instances are not the “source of truth” for the data. This property is very important to enable autoscaling. Two incoming requests may be served by two distinct server instances. When data is involved, the instances need to rely on another component, like a database. Sharing a picture with Cool Maze typically incurs 7 API calls to the servers. I use <a href="https://cloud.google.com/products/firestore">Firestore</a> as a shared short-term memory where these requests can write and read data.</p><h3>Transient memory</h3><p>For maximal performance, I also write the data to an in-memory cache local to each instance. When we’re reading data that happens to exist in the local memory, the operation is extremely fast. When the data is not in the local cache, then we read it in the Firestore database shared by all instances. This strategy works well for small resources up to 1MB.</p><p>For larger resources, such as a high-resolution photo, I use <a href="https://cloud.google.com/storage">Cloud Storage</a> (GCS) instead. In this case, the backend generates “<a href="https://cloud.google.com/storage/docs/access-control/signed-urls">signed URLs</a>” to let the mobile app write the resource to Cloud Storage.</p><p>I set an expiration policy on Firestore documents (<a href="https://cloud.google.com/firestore/docs/ttl">doc</a>) and on GCS objects (<a href="https://cloud.google.com/storage/docs/lifecycle">doc</a>). Automated expiration is perfect for ciphered data shared via Cool Maze, as a transfer takes only a few seconds, after which the encrypted payload will not be used anymore and can be discarded.</p><h3>Scalability</h3><p>The system achieves high performance even when under heavy load, because each of the cloud components has a scalable and distributed infrastructure: Firebase Hosting, Cloud Run, Firestore, and Cloud Storage.</p><p>All the “Share” actions made by all the Cool Maze users are independent from each other, thus all the clients operate only on their own data, without any contention.</p><h3>Concurrency</h3><p>In Cloud Run I leverage three levels of concurrency.</p><p>First, a user request may trigger several concurrent operations. For example, when sharing 5 photos, 5 pairs of secure URLs are generated concurrently, using <a href="https://go.dev/tour/concurrency/1">goroutines</a>.</p><p>Second, a server instance can <a href="https://cloud.google.com/run/docs/about-concurrency#maximum_concurrent_requests_per_instance">handle many incoming requests</a> concurrently. We don’t need to wait for the previous request to be finished. As each request is being served fast, and requests are processed concurrently, a single instance is usually enough to sustain all of the load.</p><p>Third, Cloud Run <a href="https://cloud.google.com/run/docs/about-instance-autoscaling">automatically starts new instances</a> when CPU utilization reaches a treshold, or when too many requests are queueing. This horizontal scaling works smoothly, as the stateless instances never need to communicate directly with each other. As I wrote the server in Go, we enjoy a fast instance startup, and powerful concurrency within each instance.</p><h3>Server push</h3><p>When the mobile app sends a message to the cloud backend, it makes a traditional HTTPS request. But then the cloud backend needs to notify the web browser currently displaying the QR code. How can a server effectively initiate a message to a client? I solved the “Server push” problem by (ab)using the Firestore <a href="https://firebase.google.com/docs/firestore/query-data/listen">realtime updates</a> capabilities. Firestore can notify a client currently “listening” to the changes of a document. This database feature was designed to let apps always display the fresh, up-to-date value of their data. I built a message bus on top of it, by having the webpage listen to a specific “Message” document. The backend writes to this document, and the webpage is promptly notified and receives the message contents.</p><h3>Analytics</h3><p>The backend asynchronously writes anonymous usage information to a <a href="https://cloud.google.com/bigquery">BigQuery</a> dataset: size of the data shared, duration of ciphering and upload, duration of download and deciphering, approximate location (country and city), etc. This dataset is the source of fantastic analytics insight, that I will present in details in upcoming articles on the Cool Maze blog.</p><h3>Give it a try!</h3><p>I use Cool Maze every day, and I forget how casual transfer used to be done before (via email, maybe?). You too can use it for free! The app is available <a href="https://play.google.com/store/apps/details?id=com.bartalog.coolmaze">for Android</a> and <a href="https://apps.apple.com/us/app/cool-maze/id1284597516">for iOS</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*mCjAlLvZIspbBlu2JzxgeQ.png" /></figure><p><em>This article was cross-posted from </em><a href="https://blog.coolmaze.io/posts/006-cloud-architecture/"><em>The Cool Maze blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6739e7fea03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/the-cloud-architecture-of-cool-maze-f6739e7fea03">The cloud architecture of Cool Maze</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improved benchmark syntax in Go]]></title>
            <link>https://medium.com/@val_deleplace/improved-benchmark-syntax-in-go-b1fc3869ffa2?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1fc3869ffa2</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 13:45:45 GMT</pubDate>
            <atom:updated>2025-03-28T13:47:57.137Z</atom:updated>
            <content:encoded><![CDATA[<p>The tooling for <a href="https://pkg.go.dev/testing#hdr-Benchmarks">microbenchmarks</a> in Go is awesome, as it is easy to use and has an idiomatic form understood by the community.</p><p>The code required to write a benchmark is now getting even better!</p><p>Here is the classic benchmark form:</p><pre>func BenchmarkComputation(b *testing.B) {<br>    p := setupComplexProcessor()<br>    b.ResetTimer()<br><br>    for i := 0; i &lt; b.N; i++ {<br>        Sink = p.ExpensiveComputation(42)<br>    }<br><br>    b.StopTimer()<br>    p.Cleanup()<br>}<br><br>var Sink float64</pre><pre>$ go test -bench=.<br>BenchmarkComputation-10                 1267     952379 ns/op</pre><p>The integers i and b.N are artifacts of the testing.B type, which is responsible for choosing the exact number of times your code must be executed, and lets you write the for loop.</p><p>The Sink exported variable is a precaution to prevent the compiler from being “too smart”. In theory, the compiler could detect that p.ExpensiveComputation is a pure function, and its result is never actually used. It could then decide to remove the function call altogether, leaving an empty loop body whose performance numbers are meaningless and misleading. When assigning the result to an exported variable, the compiler cannot make these assumptions and we know the function will actually be called at runtime.</p><p>b.ResetTimer() and b.StopTimer() are making sure the time spent in setup and cleanup is excluded from the recorded durations, and does not skew the numbers. The only section we want to measure is the code inside the loop body.</p><p>What if we could get rid of all this kipple? Good news, here is the new idiomatic style in Go 1.24:</p><pre>func BenchmarkComputationNewStyle(b *testing.B) {<br>    p := setupComplexProcessor()<br><br>    for b.Loop() {<br>        p.ExpensiveComputation(42)<br>    }<br><br>    p.Cleanup()<br>}</pre><pre>$ go test -bench=.<br>BenchmarkComputationNewStyle-10         1058     953349 ns/op</pre><p>The powerful new <a href="https://pkg.go.dev/testing#B.Loop">Loop</a> method allows us to not write i , b.N , Sink , ResetTimer , StopTimer in our code anymore.</p><p>No more explicit number of iterations: b.Loop() will return false “when the work is done”.</p><p>It also resets the benchmark timer the first time it is called, and stops the timer when returning false .</p><p>The compiler never optimizes away calls to functions within the body of for b.Loop() { … } , thus we don’t need to introduce a Sink variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IO1dk5g1C4EHHtCtybX_NA.png" /><figcaption>I love deleting code</figcaption></figure><p>Bonus: BenchmarkComputationNewStyle(), with its setup and cleanup overhead, is only called once by the go test tooling. The Loop method figures out the total number of loop iterations needed. The overhead code used to be called several times, in the classic benchmark form.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1fc3869ffa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using maps as sets]]></title>
            <link>https://medium.com/@val_deleplace/using-maps-as-sets-7de3ca01d4a7?source=rss-5c7fb9360a28------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de3ca01d4a7</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Val Deleplace]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 12:49:16 GMT</pubDate>
            <atom:updated>2025-01-23T10:05:12.919Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, there is no built-in type for <a href="https://en.wikipedia.org/wiki/Set_(abstract_data_type)">sets</a> and it is standard practice to use a map instead. The idea is to consider only the keys of the map (which is an efficient hash table under the hood), while ignoring the values.</p><h3>Empty structs</h3><p>The empty struct type struct{} is a cromulent choice for the values, as it contains no data, takes no memory, and exists only as a unique (empty) value.</p><pre> // Create the set s<br> s := make(map[T]struct{})<br><br> // Add elements<br> s[a] = struct{}{}<br> s[b] = struct{}{}<br><br> // s will not contain duplicate values<br> s[b] = struct{}{}<br><br> // Print the elements<br> for v := range s {<br>         fmt.Print(v, &quot; &quot;)<br> }</pre><p>Try it <a href="https://go.dev/play/p/2vEtN6ncz_F">in the playground</a>.</p><p>The only drawback is the struct{}{} ugly, cryptic value. You may rename it if you find it more legible (YMMV):</p><pre>type Ø struct{}<br><br>var ø = Ø{}<br><br>s := make(map[T]Ø)<br>s[a] = ø</pre><p><a href="https://go.dev/play/p/6nrRapracGf">Playground</a>.</p><h3>Booleans</h3><p>It is also common to use the bool type for the values.</p><pre> // Create the set s<br> s := make(map[T]bool)<br><br> // Add elements<br> s[a] = true<br> s[b] = true<br><br> // s will not contain duplicate values<br> s[b] = true<br><br> // Print the elements<br> for v := range s {<br>         fmt.Print(v, &quot; &quot;)<br> }</pre><p><a href="https://go.dev/play/p/RlcZUK6OB-D">Playground</a>.</p><p>This practice comes with a <strong>big gotcha</strong>: you insert elements by setting the value to true , but you <strong>cannot</strong> remove them by setting the value to false . You have to use the built-in function delete .</p><pre>// Don&#39;t do this!<br>s[a] = false<br><br>// This is the correct way to remove an element<br>delete(s, a)</pre><p>Using the value false would lead to wrong values of len(s) , and to complications for membership testing.</p><h3>Membership test</h3><p>With the map[T]struct{} implementation, testing if the set s contains the value x consists of checking if the key x exists in the map:</p><pre>_, ok := s[x]</pre><p>With the map[T]bool implementation, the map value can be interpreted directly as membership and used in a conditional clause:</p><pre>if s[x] {<br>        // x is a member!<br>        ...<br>}</pre><h3>Encapsulation</h3><p>To work around the oddities of the syntax necessary to access a map and ignore the values, consider wrapping the map in your own type, or using a third-party library.</p><pre>type Set[T comparable] struct {<br>        m map[T]struct{}<br>}<br><br>func NewSet[T comparable]() Set[T] {<br>        return Set[T]{<br>                m: make(map[T]struct{}),<br>        }<br>}<br><br>func (s Set[T]) Add(t T) {<br>        s.m[t] = struct{}{}<br>}<br><br>func (s Set[T]) Remove(t T) {<br>        delete(s.m, t)<br>}<br><br>func (s Set[T]) Contains(t T) bool {<br>        _, ok := s.m[t]<br>        return ok<br>}<br><br>func (s Set[T]) Len() int {<br>        return len(s.m)<br>}<br><br>func (s Set[T]) Values() []T {<br>        return slices.Collect(maps.Keys(s.m))<br>}</pre><p><a href="https://go.dev/play/p/y2eauR2_gIK">Playground</a>.</p><p>Bonus: have you heard of the <a href="https://medium.com/google-cloud/new-iterators-in-go-1-23-5d4596e50760">new iterators introduced in Go 1.23</a> ? Consider returning the values of the set as an <a href="https://pkg.go.dev/iter#Seq">iter.Seq</a> :</p><pre>func (s Set[T]) Values() iter.Seq[T] {<br>        return maps.Keys(s.m)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de3ca01d4a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>