Using Golang Iterators for Efficiency

TL;DR In this blog post, we will see how new golang iterators1 enables us to write efficient code. Although, we talk about iterators in golang, same argument holds for other languages as well2. Traditional Approach Consider a hypothetical example of writing powerset function to generate all possible subsets: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // We are using slice instead of set func PowerSet[T any](values []T) [][]T { if len(values) == 0 { return nil } results := make([][]T, 0) for i := 0; i < int(math.Pow(2, float64(len(values)))); i++ { result := make([]T, 0) for j := 0; j < len(values); j++ { if i&(1<<j) != 0 { result = append(result, values[j]) } } results = append(results, result) } return results } What is going on here: ...

November 10, 2024 · 581 words · Vivek Akupatni

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

Populating Java PriorityQueue Efficiently

TL;DR Use PriorityQueue constructor(s) to populate elements in queue instead of addAll, add or offer methods Couple of weeks back, I was going over PriorityQueue docs in Java and wondered if there is any difference in performances over how Priorityqueue is constructed. After some analysis, I realized that it does make a difference how tree is constructed. In this blog post, I try will to explain the reasons and provide some actual benchmarks with some sample test cases. ...

October 10, 2021 · 627 words · Vivek Akupatni