Preallocate Java's ArrayList And HashMap For Better Performance

TL;DR Preallocation avoids unnecessary memory reallocations due to dynamic resizing, copying of the data, rehashing for maps and puts less pressure on GC1. Although we will only look at Java, the same behavior exists in c++, rust and many other languages as well. ArrayList There are two ways to create an ArrayList . Method 1: Created with zero argument constructor. This uses a default capacity of size 102. var arr = new ArrayList<String>(); arr.add(elem) // add something later Method 2: Provide an initial capacity with int argument constructor. ...

August 21, 2022 · 1105 words · Vivek Akupatni