DEV Community

Cover image for Growing Pains: How Dynamic Arrays Handle New Elements ?
Abhiru Karki
Abhiru Karki

Posted on

Growing Pains: How Dynamic Arrays Handle New Elements ?

Dynamic Arrays might seem simple at first glance, but their inner workings will open your eyes đź‘€.

But first of all, let's start with the basics.

What are Dynamic Arrays ?

Dynamic Arrays are resizable arrays that can automatically adjust their size when elements are added âž• or removed âž–.

Unlike Static Arrays which has a fixed size that is determined during compile time, the size of Dynamic Arrays can be adjusted during run time as per the need.

But are Dynamic Arrays really Dynamic ?

Actually Dynamic Arrays are built on top of Static Arrays. Surprising right ? Let's dive deeper 🤿

The Working Mechanism ⚒️

Suppose we have a Dynamic Array myArr[3] = {2, 4, 6} which is already full.

Image description

Now, If you want to add a new element to the array according to Dynamic Array, you may think that a new slot will be added to the existing array and the element is then after inserted into it. What if I tell you "YOU ARE WRONG" ? 🤨

The Moment of Truth âś…

What actually happens is that a new array is created with double or greater capacity than the existing array ( no worries, will explain the reason for this too ) , and all of the existing elements are shifted to the new array, as well as new elements, and then the pointer head 🫵 is shifted from the previous array to the new array 🫵, and the previous array is deallocated if necessary.

Image description

Now why the new array has double or much greater capacity than the previous array ? 🤨

It's simple.
So that we don't run out of space frequently, which would require us to create a new array every time we add a single new element, increasing the time complexity of the process. Instead, why not just create a little larger but not too large new array to balance the time and space complexity ?

So yeah that was it 🤷

Now you know how Dynamic Arrays actually work. Understanding the mechanics of dynamic arrays is crucial for efficient programming.

As you continue your coding journey, keep these principles in mind to optimize your data handling strategies. Happy Coding!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more