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

Python Logging Good Practices

Logging library in python has been in standard library since a very long time. In many aspects, this logging framework bears similiarties with log4j libraries in Java. In this blog post, I will go over some of the good approaches when using python log formatting. Avoid using root logger Avoiding root logger provides the following benefits: Better descriptive names regarding where the log originated from. Helps during searching of logs Allows better log customization Many times, we find it quite easy to start logging using logging.info/logging.error methods. However, using any of the methods under logging module will result in root logger being invoked. Take a look at the examples below involving two modules: logger_usage.py and user_record.py ...

July 9, 2022 · 671 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