<?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 RandomDev on Medium]]></title>
        <description><![CDATA[Stories by RandomDev on Medium]]></description>
        <link>https://medium.com/@random-dev?source=rss-48fdce0b577------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*taJijBYfpSwZW0PvEXY3tg.jpeg</url>
            <title>Stories by RandomDev on Medium</title>
            <link>https://medium.com/@random-dev?source=rss-48fdce0b577------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:34:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@random-dev/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[[How it Works] Memory and Performance. Part 2.]]></title>
            <link>https://medium.com/geekculture/how-it-works-memory-and-performance-part-2-66da2edcbaf?source=rss-48fdce0b577------2</link>
            <guid isPermaLink="false">https://medium.com/p/66da2edcbaf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programing]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[RandomDev]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 23:02:22 GMT</pubDate>
            <atom:updated>2021-06-29T23:02:22.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJvGPMcQWn5GX2-p" /><figcaption>Photo by <a href="https://unsplash.com/@umby?utm_source=medium&amp;utm_medium=referral">Umberto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This part will focus mostly on OS (Operating System) layer of memory management. It doesn’t matter in which language you have written your program, from OS perspective it’s a process. Let’s see what is staying between our programming language abstraction and hardware. Once we will have a good grasp, we will explore how we can take advantage of this knowledge. But before that, quick recap.</p><p><a href="https://medium.com/geekculture/how-it-works-memory-and-performance-part-1-83cf3bc167a7">In the previous article</a>, we covered memory basics (please read part 1 in case you haven’t). We learned about main types of memory and most important characteristics of it from a performance point of view. Also, I introduced you to linear memory model and briefly touched memory segments, call stack and stack frames. We also explored the access time and fragmentation problem and how memory managers and garbage collectors attempts to solve this.</p><p>When all segments of your program are loaded into RAM …</p><p>Hold on ! I have a question ! You told me that when my program will run into a “high fragmentation state”, memory manager will use… will use … ah yes, <strong>compaction</strong> ! It will magically copy chunks of memory and fix everything. But I don’t get one point, if the memory chunk was moved, this means the memory address was changed also, right ?</p><p>Well… It depends. I oversimplified a few things there. You see, your program lives in ̶M̶a̶t̶r̶i̶x̶ a <strong>virtual memory space</strong>. Each process has a layout, as we discussed, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*_R3E3yBLXds9Gqax" /><figcaption>On the left — Memory address. On the right — actual data divided into few logical segments.</figcaption></figure><p>You may have 10 processes and each one will think his static segment starts at 0x1000. All processes may run in parallel and without any issues. More than that, each process will never be able to access memory of any other process.</p><p>Okay, you are not helping. It is even more confusing. Memory address isn’t real ? How about CPU memory address lookup you were telling me about ?</p><p>Relax, both memory addresses exists, physical and virtual. CPU is using physical address, processes are using virtual addresses, that’s it. When a process want to access something, it will provide a virtual address, OS will intercept that request and translate it into a physical address (with some help from hardware). OS will create and maintain a virtual to physical memory mapping.</p><p>Ok, now it’s a bit more clear, but I still have questions… If we want to map 1 virtual address to 1 physical address, we’re going to need a lot of memory. One memory address is related to 1 byte of data, right ? Now, we need to store somewhere the relation between two memory addresses, virtual &lt;-&gt; physical, which will still be related to a single byte of data. If the address take 32bit (4 bytes), 2 addresses will take 32+32=64bit (4+4=8 bytes) and all this is just to point to a single byte of data ! We have 8 bytes of mapping information for a single byte of actual data. Huston, we have a problem!</p><p>You are absolutely right! This is not efficient at all. That’s why we are splitting our memory into chunks. These chunks are called <strong>memory pages</strong>. Instead of keeping track of virtual to physical mapping for each byte, we can do this for larger blocks.</p><p>Let’s assume we have a page of 4kB (4096 bytes) and a memory address which takes 32bit (4 bytes). If we spend 8 bytes for two addresses from each chunk of 4096 bytes this is ~ 0.19% of memory wasted on mapping. Not too shabby! By the way, this mapping is called a <strong>page table. </strong>And the pair of addresses virtual to physical is called <strong>page table entry. </strong>OS is in charge of all this and will create one page table per process. Pay attention here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*JVuOZB8qwhI5gmFH" /><figcaption>Visualization of Virtual and Physical memory. Page 1 from virtual memory space is associated with Page 1 from physical memory space, and so on…</figcaption></figure><p>Each page from virtual memory is associated with a page in physical memory (RAM). The order and location of pages in physical memory may be different from the virtual one. Both pages, virtual and physical have a fixed size. From a process perspective, the memory will always be continuous. This also means your process can’t reserve a single byte of memory, it can reserve at least a single page of memory, this leads to wasted memory often because the memory consumption usually is not exactly a multiple of a page size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*E3mm5dRzcktsf2xh" /><figcaption>A snapshot of 3 different memory pages.</figcaption></figure><p>In the image above, you can see that in Page 1, the program is using only 3072 (3 x 1024 bytes blocks), the last block of memory is not used and can’t be reserved by other programs. Page 3 is used at 100% of its capacity, so we are not wasting memory at all. The worst case here is Page 2, only ¼ of the page is effectively used by a program.</p><p>Ok, I got it. If we have bigger memory pages, we can potentially waste more memory, but at the same time we can’t have a single byte sized page because the page table will be huge then. Why we need all this “virtuality” then ?</p><p>The primary benefit is that developers don’t have to manage a shared memory space. For example, we don’t need to decide where in memory to allocate space for a variable without breaking other running processes. Writing a simple “hello world” would be a serious challenge, requiring you to know all kinds of memory management things. Besides this, we also benefit from increased security (memory isolation) and few other things like swapping and caching, which we will touch in a moment.</p><p>Before going to the next benefit of virtual memory, let’s talk a bit about performance. Now we know that every memory access will involve an additional operation — virtual to physical mapping lookup. Finding the entry in the <strong>page table</strong> every time can be very costly. To solve this problem, modern computers have to maintain a very fast caching solution. And by very fast, I don’t mean RAM itself of course, because from a CPU perspective RAM is too slow. This solution is called <strong>TLB</strong> (translation look-aside buffer), and for best performance it is located typically right inside the <strong>MMU</strong> (Memory Management Unit) in CPU. The TLB is very fast and can return the right address in a single clock tick or less (<a href="https://en.wikipedia.org/wiki/Translation_lookaside_buffer#Typical_TLB">Read More Here</a>). The problem with TLB is that it have a limited size, thus it can’t hold many page table entries, if the entry is not found in TLB it will have to be searched “manually” which is expensive (may cost x10-x100 more).</p><p>Going back to our page sizes, larger page means fewer entries in page table; fewer entries means more profit from TLB. A smaller memory page means we will have to store more virtual-physical mappings, which means we will have more entries in our page table. Many entries may fill out TLB capacity, leading to a higher probability of more expensive “manual” searches.</p><p>But, virtual memory not only simplify software development, it can also help you to improve your performance.</p><p>Wow ! This is good, because so far I see only convenience at price of performance. What next ?</p><p>Next is <strong>Page cache.</strong></p><p>Let’s imagine we have an application which periodically needs to read some information from your disk. We already know what is access time and how it can affect the performance, so wouldn’t be cool to have a smart way of caching it into RAM instead of accessing it from your HDD/SSD each time? Don’t tell anything, of course — Yes! Your OS is always tracking the memory demand and can cache files for you if you have a lot of unused memory. Isn’t this cool? And you don’t even have to bother by coding this.</p><p>When a file is accessed by your program, the page caching algorithm will load that file into the page cache (RAM) and then return the data to your program from the page cache. The next attempt to read something will return data from RAM instead of accessing it from disk, thus improving the performance at the price of higher RAM usage.</p><p>The same can happen when you write files. If a program writes small chunks of data frequently (Ex: logging) it will go first to the page cache. If the file we are about to write is in cache it will be marked as “dirty” after changes, this means that the cached file and the actual file on the disk is different now, and it needs to be flushed to disk. Page cache can batch few changes before flushing it to disk, once it is flushed the cache is marked as “clean” (means disk version and cached version is the same).</p><p>And what if I read only the first part of the file? Loading the whole file into RAM will not only decrease the performance, this can lead to using an excessive amount of memory in case of big files.</p><p>Hold on, your OS is smart and can cache chunks of files also. In the image below, only the first part of the file was requested by the process. If the process need to read that chunk again later, it will be served from page cache instead of accessing the disk, which results in a significant performance gain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*BYIQxwcfCjnnP2kA" /><figcaption>A chunk of file on disk is loaded into RAM into a specific page cache then served to a process directly from RAM.</figcaption></figure><p>What is even greater is that by having virtual to physical memory mapping + file to memory mapping, we can trick our programs into reading the page cache directly, thus eliminating RAM to RAM copy also.</p><p>Wow! This is cool!</p><p>Yes, it is! You know what is even cooler?</p><p>What?</p><p>Processes can share the same file. If your program requested a read for a file that is already mapped in cache, it will read it directly from cache, which means, again, increased significant performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*vYLXN4BXchNZvUal" /><figcaption>2 different processes are reading the same file using the same page cache.</figcaption></figure><p>Or, in case you don’t have enough RAM for your programs, it can start writing things into disk (<a href="https://wiki.archlinux.org/title/Swap">swap file</a>) instead of RAM, but this will have obviously a negative impact over performance.</p><p>Hey, how knowing this stuff can help me with my programs if I don’t have control over this ?</p><p>Good point. These techniques will work in your favor 99% of time. But if you are designing heavy I/O programs, this may become an extremely annoying thing. And <strong>No</strong>, <strong>you Have control </strong>over this!</p><p>For DB systems keeping too much cache dirty is a concern because RAM as we remember is volatile, in case of power losses the changes from cache will be lost forever. There are other reasons as well, here you can find a tuning recommendation for Oracle Database (<a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/tuning_and_optimizing_red_hat_enterprise_linux_for_oracle_9i_and_10g_databases/sect-oracle_9i_and_10g_tuning_guide-memory_usage_and_page_cache-tuning_the_page_cache">Tuning the Page Cache</a>).</p><p>Sometimes, page caching, and write batching can cause disk I/O jitters. Basically what is happening, is that OS keeps in RAM a large portion of write operations then flush it all at once. If the amount of write operations accumulated is higher than disk I/O capacity, it will block all other disk I/O-s causing decreased performance of the system overall. This could be easily solved with some simple OS tuning. Easily if you know these things :).</p><p>Here is an overly-simplified graph to help you to understand it better. The average load is the same, but tuning can help you get a more smooth I/O load profile.</p><p>On the Red line, the period of times when disk I/O is fully saturated (100%), the system will can’t handle anything additional and typically will suffer from spikes in latencies. The smooth blue line will behave much better and even unlock your application to handle potentially more load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*D_-paJHyxfvS-owY" /><figcaption>Simplified visualization of suboptimal page cache configuration (red line) and tuned page cache configuration (blue line).</figcaption></figure><p>If you are not convinced by this theoretical situations, you can find real life examples. There are some excellent articles, for example a server running Kafka was struggling with I/O jitters and sporadic latencies: <a href="https://developpaper.com/application-of-linux-page-cache-tuning-in-kafka/">Linux page cache tuning for Kafka</a>. If that is not enough, take a quick look <a href="https://discuss.aerospike.com/t/how-to-tune-the-linux-kernel-for-memory-performance/4195">Aerospike guide for tuning Linux Kernel</a> which is facing the same problem. This should help you recognize and understand this kind of problem in the future. Even if you are a java developer, there are <a href="https://github.com/smacke/jaydio">libraries</a> which can help you to bypass OS caching and obtain maximum performance for your specific case.</p><p>That’s it! Thank you for reading this, hope you will find it useful. If you have any suggestions for future articles, feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66da2edcbaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-it-works-memory-and-performance-part-2-66da2edcbaf">[How it Works] Memory and Performance. Part 2.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[How it Works] Memory and Performance. Part 1.]]></title>
            <link>https://medium.com/geekculture/how-it-works-memory-and-performance-part-1-83cf3bc167a7?source=rss-48fdce0b577------2</link>
            <guid isPermaLink="false">https://medium.com/p/83cf3bc167a7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[RandomDev]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 15:59:23 GMT</pubDate>
            <atom:updated>2021-06-26T18:22:26.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZuYsN5L-_0q9zcJq" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are a software engineer and care about performance, this article is for you. It doesn’t really matter what language you prefer, C, C++, Java, Python, GO etc… What I will try to cover here should give you an insight on what happens with your computer memory under the hood. Because basically every program interact with memory, it is crucial to have a good knowledge of it.</p><p>I will try to cover it in depth and provide a few examples from the real world, but don’t expect this to be a collection of “best practices” and advices. You will be the one who will give advices after reading this :). The power is in knowledge and not in blind rule-following.</p><p>If you are a beginner, don’t worry, I will make sure we are covering the basics.</p><p>Ok, let’s start with basics. Computer memory means many things, let’s classify them by volatility first.</p><p>Now we have two types, volatile and non-volatile (don’t be annoying and ignore semi-volatile type please).</p><p><strong>Non-volatile memory</strong></p><p>Non-volatile memory is computer memory that can retain the stored information even when not powered. We will briefly cover HDD and SSD in this article.</p><figure><img alt="HDD. Hard Drive Disk" src="https://cdn-images-1.medium.com/max/1024/0*CUoAsXHB7tyUiG3D" /><figcaption>HDD. Hard Disk Drive.</figcaption></figure><p><strong>HDD</strong>. You most probably heard about HDD (Hard Disk Drive) before, it’s a piece of “magnetic disk” that spins crazy fast and can read/write your precious information. The main advantage over other non-volatile storage types is the balance between capacity and cost.</p><p>To read something, you will need to seek your file on the surface of the disk with magnetic heads and start translating magnetic fields into bytes. You may ask, what if my file is huge and is spread across the surface of the disk (also known as <strong>fragmentation</strong>)? Well, you will spend more time. Because time that we wait the disk to spin to the next file fragment is a wasted time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*gWFJVkSw6HlLvUeP" /><figcaption>On left. High fragmentation, 5 spins required. | On Right. No fragmentation, less than 1 spin required.</figcaption></figure><p>Because of the design, we have the following characteristics:</p><p><strong>Fast sequential operations </strong>— you will waste time to find the file but if the file is not spread you will be able to read it in one go!</p><p><strong>Slow random operations</strong> — reading/writing files in random places on surface of disks adds a significant overhead because magnetic head have to travel to each place, often, in multiple spins.</p><p>By the way, the time it takes for a magnetic head to move to the desired location is also known as <strong>access time</strong>. Other memory types don’t have magnetic head, but still have access time penalty, keep this in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UGmDeQbunwQxreGJ" /><figcaption>SSD<strong>.</strong> Solid State Drive.</figcaption></figure><p><strong>SSD</strong> (Solid State Drive). This one doesn’t have any physical spinning disks or moving parts, so you can expect better <strong>access time</strong>, thus superior random read/write operations. Generally speaking, SSD are usually around x10 times faster than HDD. Of course, this speed is a bit pricey, for the same money you will have less capacity if compared to HDD.</p><p><em>Did you know that some computer games have to duplicate data (typically textures) to make sure the HDD keeps reading things sequentially ? Knowing this small thing helps developers to improve significantly the performance. This technique isn’t however optimal for SSD because access time have small overhead.</em></p><p><strong>Volatile memory</strong></p><p>Volatile memory is computer memory that requires power to maintain the stored information. We will talk about RAM a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTRyWiiZ2ULlzmIf" /><figcaption>RAM. Random Access Memory.</figcaption></figure><p><strong>RAM</strong>. (Random Access Memory) As the name suggests, this one allows information to be read or written in <strong>almost </strong>the same amount of time, irrespective of the physical location of data inside the memory. Typically, it is x1000 faster than SSD/HDD. It’s also super expensive if compared to HDD/SSD and will have a hundred times less capacity.</p><p>Let’s recap memory characteristics:</p><p><strong>Capacity </strong>— it’s about how much data we can store.</p><p><strong>Volatility </strong>— how does memory behave when there is no power.</p><p><strong>Access time</strong> — how much time we need to find the physical location of our data.</p><p><strong>Fragmentation </strong>— how much our data is broken up into many pieces that are not close together physically.</p><p>To go further, we will need to agree on a way to represent memory visually. <strong>Flat memory model </strong>or <strong>linear memory model</strong> is the most common memory addressing paradigm, we built a lot of abstraction layers above this, but be patient, we will cover that later. In modern computer architectures, one memory address points to one byte of data. Here is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*bi_smBM6KTajoAFX" /><figcaption>Linear memory model.</figcaption></figure><p>Wait a second! If one byte of information is associated with an address, then the address itself should take some space from your memory, right? If we spend 1 byte to store address then 1 byte to store information itself, then we will have 50% of memory wasted just to keep track of addresses. It’s madness!</p><p>Yes it is! That’s why nobody is doing that :). Instead of this, modern computers just “count” each time “memory cells”. Memory address is just a number of bytes the CPU will skip from the beginning of the memory to get to the one it’s looking for. For example:</p><ul><li>To access the first byte, it has to skip 0 bytes, so the first byte’s address is 0.</li><li>To access the second byte, it has to skip 1 byte, so its address is 1.</li><li>(and so on…)</li></ul><p>You got the idea, right?</p><p>Okay, but I heard about limitations like 32 bit CPU-s can’t have more than 4GB or RAM, why?</p><p>Oh, I like your questions. The thing is that when you instruct your CPU to do something, you will have to call a special function with a parameter. Let’s imagine we are calling “goto 1000”, which means go to memory address 1000. The CPU have to store this number somewhere, then pick up that instruction and execute. This storage cell is called a CPU register, and the capacity of that register is limited to 32 bits. The highest number you can store in 32bits is 2<strong>³²</strong> (or 4294967296) which is 4Gb. This means you can’t tell to your CPU to go to a memory address above that number. You can have more RAM, but the CPU will not be able to read/write anything above that limit. Luckily, most modern computers have now 64bit architecture (but not always 64bit registers), which means it will be able to work with 16 exabytes (2<strong>⁶⁴</strong> bytes) of RAM (sadly, it will cost a lot, don’t expect to have this in your average home PC).</p><p><em>Good to know. Memory access to RAM is relatively slow from CPU perspective, and may take a number of clock ticks to complete. Memory access to registers is very fast (usually one clock tick). To overcome this issue, modern CPUs will use memory cache.</em></p><p>But what if my program need to use numbers higher than 255 (1 byte)? How this will be stored in RAM?</p><p>Not a problem! All you need to know is the memory address where your integer starts and how many bytes it takes. In the image below, you can see how a 2 byte integer is stored in memory. We will start to read the data at address 0x6000 and stop at address 0x6001.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*4daeUiD0cMcwfc2D" /></figure><p>Great! Now we know the basics. We know about different memory types and main characteristics of memory. Also, we learned a bit about linear memory model and how CPU is accessing it. Let’s move on to programs.</p><p>Let’s start with the basic workflow of a program and see how it works from a memory perspective. But before that, how we are making these programs? Generally you have simple text files which we are calling <strong>source files</strong>, then using your language specific compiler you compile it into an <strong>executable file</strong>.</p><p>Hey, I am a programmer, I obviously know it!</p><p>Okay, okay… The executable file contains instructions readable by your OS and CPU. There are two main pieces in the executable file: <strong>data</strong> (contains global variables, constants, other static data), and <strong>code</strong> (contains your compiled functions).</p><p>OK, clear… But how my program end up being in RAM?</p><p>I am glad you asked! This part of the job is being handled by Operating System <strong>Loader</strong>. When the user executes the executable file, “the loader” will make sure to allocate memory for your program and then will copy it right into your <em>Operative memory</em> (RAM). But this all isn’t that simple! We need to go deeper! Typically, OS loader will split allocated memory into a few <strong>memory segments</strong>.</p><p>There are four memory segments which we will cover: <strong>code</strong> (obviously, your compiled functions), <strong>static</strong> (that data part from executable file), <strong>stack</strong> and <strong>heap</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*sspk9QZb_bc_vdypUx3ojw.png" /><figcaption>Program Memory Segments.</figcaption></figure><ul><li><strong>Code segment</strong>: usually is marked as read-only by the loader (this feature depends on OS) so that CPU will not be able to overwrite this address range. If an attempt will be made to change this segment, OS may detect it and abort the program immediately.</li><li><strong>Static segment</strong>: the size of this segment will be fixed, it will persist in memory while the program is running. Doesn’t matter if you are using it or not. In contrast to the previous segment, this one can be changed during execution.</li><li><strong>Stack segment </strong>(aka call stack): If the static segment contains global variables and constants, this one contains local variables. This segment is broken into many <strong>stack frames. </strong>Stack frames are added into the stack before the function runs, and are removed after execution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*tSHS-iuukzgExVfq" /><figcaption>Call stack/Stack segment</figcaption></figure><p>A stack frame contains all needed information for one function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*cRXaODqg26mvBNq2" /><figcaption>Stack frame contains function arguments, local variables and return address</figcaption></figure><p>Function call is broken in few instructions:</p><ul><li>Allocate memory for a stack frame</li><li>Push the stack frame into the call stack</li><li>Run the function declared in the stack frame</li><li>Pop the executed stack frame</li></ul><p>As you can see, programmers will not bother too much about this. Memory will be freed and allocated automatically. Please note, the size of a frame is fixed!</p><p>Hmm, does it mean that calling functions is more expensive than writing everything as a single flow of instructions?</p><p>Yes, it has a bit of overhead, but don’t be afraid to split your logic into small functions, modern compilers are smart and will often “inline” functions. The overhead might be zero to minimal. But it’s good to be aware that going to “abstract” will not go unnoticed for performance. (<em>Maybe, one day, I will write an article on how to design your code to make use of CPU cache and other advanced techniques like branchless programming but now, we are talking about memory</em>)</p><ul><li><strong>Heap segment</strong>: this part is designed for cases when programmers need to allocate large and dynamically resizable data structures. Something which is not really possible in stack or static segment. We can control the lifecycle of the data and decide when you want to free and allocate the memory. Heap management is a very complex topic. Programming languages will implement different <strong>memory managers.</strong> These usually try to allocate a continuous block of memory which is later split into smaller chunks when you request memory reservations. In nutshell, it keeps track of what chunks are used and not. If during program execution, memory manager will allocate and free chunks of memory in an unfortunate sequence, you may end up with a very fragmented heap segment.</li></ul><p>Hey, fragmentation shouldn’t be an issue we have fast access time in RAM, right?</p><p>Well… Yes, and not really. Here is an example when RAM fragmentation may become a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*m4mZuNXHf6A4dtLUAS1MQA.png" /><figcaption>High memory fragmentation</figcaption></figure><p>We have 400 kB of total used memory and 400 kB unused memory. Now, imagine your program requires an array which will take 200kB. Even if you have 400 kB of free memory in total, you can’t find a chunk of 200kB or bigger, and you will get a memory allocation failure. A solution to this will be <strong>memory compaction. </strong>Memory what ?<strong> Memory compaction! </strong>This<strong> </strong>is the process used to relocate information blocks in main memory in order to maximize the available free space. But keep in mind, to do this you will have to do a few malloc() and free() operations. Your program must stop its execution and reorganize the memory chunks. Obviously, this is quite expensive from a performance point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*1u_ijopCpnTamqboNQJgDQ.png" /><figcaption>Memory after compaction.</figcaption></figure><p>As you can see, your programs can suffer from serious <strong>heap fragmentation</strong> leading to low utilization of memory, degraded performance, and application failure due to memory exhaustion.</p><p>Will this mean that “immutability” lead to a very high fragmentation and will put a lot of pressure on memory managers?</p><p>Most probably yes, so try to use this rationally, it’s a good solution for multithreading for a number of reasons, but excessive memory allocations will have a significant impact.</p><p><em>Remember CPU memory cache mentioned before ? Memory lookups, which are expensive from CPU perspective, can be served from cache, but cache itself have a limited capacity. High RAM fragmentation may exhaust that cache. We will cover this a bit again when we will learn about memory pages.</em></p><p>Languages like Java, Go and Python have garbage collectors which have cycles of compacting the memory. Languages like C/C++ have different memory allocators/managers which attempt to solve the same problem. Even if it looks that the problem is magically solved by memory managers and Garbage Collectors, you need to remember that compacting the memory involves additional copy operations, scans and long pauses!</p><p>That’s it for the fisrt part. In the next parts we will learn about memory alignment, memory pages, memory mapping, caching and a few performance tricks. If you are interested in the second part, please let me know in the comments. What do you think about level of details ? Is it too superficial or too complex and hard to follow? I will consider your feedback for the second part. Also, feel free to suggest the next topic if you are interested in something.</p><p>Thank you for reading this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83cf3bc167a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-it-works-memory-and-performance-part-1-83cf3bc167a7">[How it Works] Memory and Performance. Part 1.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>