How to Write Fast Code: Patterns for Patience

𝐏𝐚𝐭𝐭𝐞𝐫𝐧𝐬 𝐨𝐟 𝐅𝐚𝐬𝐭 𝐂𝐨𝐝𝐞 : 𝐁𝐞𝐲𝐨𝐧𝐝 𝐉𝐮𝐬𝐭 𝐖𝐫𝐢𝐭𝐢𝐧𝐠 𝐂𝐨𝐝𝐞 𝐓𝐡𝐚𝐭 𝐖𝐨𝐫𝐤𝐬 As an architect, I have learned that everyone can write code that runs but not everyone writes code that runs fast. Over time, I have gained a few simple patterns that make all the difference across any tech stack. Here are the some of the patterns of fast code. 𝐅𝐚𝐬𝐭 𝐜𝐨𝐝𝐞 𝐥𝐨𝐯𝐞𝐬 𝐦𝐞𝐦𝐨𝐫𝐲 𝐩𝐫𝐨𝐱𝐢𝐦𝐢𝐭𝐲 Design your data structures so the CPU can read them in a single cache line. 𝙀𝙭𝙖𝙢𝙥𝙡𝙚: 🟡 Prefer arrays or spans over scattered linked lists. 𝐊𝐞𝐞𝐩 𝐋𝐨𝐨𝐩𝐬 𝐋𝐢𝐠𝐡𝐭𝐰𝐞𝐢𝐠𝐡𝐭 A tight loop should do only essential activities. Move checks, conversions, allocations, or anything constant outside the loop. 🟡 Even tiny operations inside a loop can slow your code removing them gives the biggest speed boost. 𝐂𝐨𝐦𝐩𝐮𝐭𝐞 𝐎𝐧𝐜𝐞, 𝐔𝐬𝐞 𝐌𝐚𝐧𝐲 𝐓𝐢𝐦𝐞𝐬 Cache expensive results for unchanged inputs. 🟡Precompiled regular expressions instead of creating a new Regex every time. 🟡Using HashSet or Dictionary for repeated lookups instead of scanning a list. 𝐂𝐡𝐨𝐨𝐬𝐞 𝐭𝐡𝐞 𝐫𝐢𝐠𝐡𝐭 𝐚𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝐚𝐭 𝐭𝐡𝐞 𝐬𝐭𝐚𝐫𝐭 𝐝𝐨𝐧’𝐭 𝐨𝐯𝐞𝐫𝐜𝐨𝐦𝐩𝐥𝐢𝐜𝐚𝐭𝐞 𝐥𝐚𝐭𝐞𝐫. The performance of your code depends more on choosing the right algorithm/data structure upfront than on tiny optimizations later. 🟡 A poor choice early (like a List where a HashSet would fit) forces extra work later, no compiler trick can fully fix it. 𝐎𝐩𝐭𝐢𝐦𝐢𝐳𝐞 𝐁𝐚𝐬𝐞𝐝 𝐨𝐧 𝐅𝐚𝐜𝐭𝐬 🟡Use profilers, Stopwatch, or BenchmarkDotNet to measure hotspots. 🟡Don’t guess what’s slow measure it and optimize. 🟡Every change should be data-backed to ensure it improves performance. 𝐂𝐨𝐧𝐜𝐥𝐮𝐬𝐢𝐨𝐧 Finally, fast code isn’t about typing quickly it is about planning carefully first and then start. 𝐈 𝐛𝐞𝐥𝐢𝐞𝐯𝐞 𝐲𝐨𝐮’𝐯𝐞 𝐠𝐨𝐭 𝐭𝐡𝐞 𝐞𝐬𝐬𝐞𝐧𝐜𝐞 𝐨𝐟 𝐢𝐭. #CleanCode #CodeOptimization #PerformanceEngineering #SoftwarePerformance #HighPerformanceComputing #EfficientCode #FastCode

To view or add a comment, sign in

Explore content categories