StringJoiner vs StringBuffer vs Collectors.Joining() Performance Test

In this article we are sharing the program to identify which is the best performance provider out of StringJoiner, StringBuffer, StringBuilder and Collectors.joining() while joining/appending String.

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
public class PerformanceTest {
	public static void main(String[] args) {
		List<String> l = new ArrayList<>();
		for(int i=0;i<1000;i++) {
			l.add("12345"+i);
		}
		long start = System.currentTimeMillis();
		usingStringJoiner(l);
		long middle = System.currentTimeMillis();
		System.out.println("Time taken by StringJoiner : "+(middle - start));
		usingStringBuffer(l);
		long end = System.currentTimeMillis();
		System.out.println("Time taken by StringBuffer : "+(end-middle));
		usingCollectors(l);
		long end1 = System.currentTimeMillis();
		System.out.println("Time taken by Collectors.joining() : "+(end1 - end));
		usingStringBuilder(l);
		System.out.println("Time taken by StringBuilder : "+(System.currentTimeMillis() - end1));
	}
	
	private static void usingStringJoiner(List<String> list) {
		StringJoiner sj = new StringJoiner("|");
		list.stream().filter(code -> code != null).forEach(code -> sj.add(code));
		String s = sj.toString();
		System.out.println(s);
	}
	
	private static void usingStringBuffer(List<String> list) {
		StringBuffer buf = new StringBuffer();
		list.stream().forEach(code -> buf.append(code).append("|"));
		String output = buf.toString();
		if (output.endsWith("|")) {
			output = output.substring(0, output.length() - 1);
		}
		System.out.println(output);
	}
	
	private static void usingCollectors(List<String> list) {
		String str = list.stream().collect(Collectors.joining("|"));
		System.out.println(str);
	}
	
	private static void usingStringBuilder(List<String> list) {
		StringBuilder builder = new StringBuilder();
		list.stream().forEach(code -> builder.append(code).append("|"));
		String output = builder.toString();
		if (output.endsWith("|")) {
			output = output.substring(0, output.length() - 1);
		}
		System.out.println(output);
	}
}

Time taken by StringJoiner : 49
Time taken by StringBuffer : 2
Time taken by Collectors.joining() : 4
Time taken by StringBuilder : 3

If you observe the above statistics of StringJoiner and Collectors.joining(), StringJoiners are taking 49 milliseconds to complete the task where Collectors.joining() is taking only 4 milliseconds which is 45 milliseconds lesser. Here one point I would like to bring to your notice is, StringJoiner is used in the implementation of joining() in Collections. But, when I use StringJoiner externally, it is taking more time than how joining() performing.

public static Collector<CharSequence, ?, String> joining(
CharSequence delimiter, CharSequence prefix, CharSequence suffix) {
    return new CollectorImpl<>(
            () -> new StringJoiner(delimiter, prefix, suffix),
            StringJoiner::add, StringJoiner::merge,
            StringJoiner::toString, CH_NOID);
}

StringJoiner internally uses StringBuilder to store value.

/*
 * StringBuilder value -- at any time, the characters constructed from the
 * prefix, the added element separated by the delimiter, but without the
 * suffix, so that we can more easily add elements without having to jigger
 * the suffix each time.
 */
private StringBuilder value;

/* preparing StringBuiler object in StringJoiner */
private StringBuilder prepareBuilder() {
  if (value != null) {
    value.append(delimiter);
  } else {
    value = new StringBuilder().append(prefix);
  }
  return value;
}

StringBuilder has been used across all the methods of StringJoiner to perform various operations. There is one more option of using StringUtils.join() method to perform similar operation. I would like to suggest to use StringBuffer than StringUtils because it internally uses the StringBuffer only to store value.

B+ Tree Design

Introduction

B+Tree consists of root it may have n number of child nodes. Each child may have its child nodes.
If a node doesn’t have any child then we can consider that is the leaf.

  1. In B+Tree every node has one parent node (if it’s not a root node)
  2. Each Node may have n number of child nodes(if it’s not a leaf node)
  3. Each node has its properties

Use Case:

Take any corporate IT organization which has n number of employees,
each employee has its properties like id, name, salary, reporting id and reported persons We can assume sample employee data in DB

EMPID NAME DESIGNATION SALARY REPORTING_ID
1 SUBBU C.E.O 200000 NULL
2 RANGA MANAGER 200000 1
3 KIRAN MANAGER 333333 1
4 RAJU TEAM LEAD 2222222
5 MOHAN TEAM LEAD 11111112
6 CHANDRA TEAM LEAD 000000 2
7 KANTH DEVELOPER 7777777 4
8 MANI DEVELOPER 88888888 4
9 HARI DEVELOPER 66666666 5

We have to make it above raw data to B+ tree using java

when we run this application root node will have all employees info so it will display JSON data like the below

{
     "id": 1,
     "empName": "SUBBU",
     "salary": 200000,
     "designation": "C.E.O",
     "reportedEmployees": [
         {
             "id": 2,
             "empName": "RANGA",
             "salary": 200000,
             "designation": "MANAGER",
             "reportedEmployees": [
                 {
                     "id": 4,
                     "empName": "RAJU",
                     "salary": 222222,
                     "designation": "TEAM LEAD",
                     "reportedEmployees": [
                         {
                             "id": 7,
                             "empName": "KANTH",
                             "salary": 7777777,
                             "designation": "DEVELOPER"
                         },
                         {
                             "id": 8,
                             "empName": "MANI",
                             "salary": 88888888,
                             "designation": "DEVELOPER"
                         }
                     ]
                 },
                 {
                     "id": 5,
                     "empName": "MOHAN",
                     "salary": 1111111,
                     "designation": "TEAM LEAD",
                     "reportedEmployees": [
                         {
                             "id": 9,
                             "empName": "HARI",
                             "salary": 66666666,
                             "designation": "DEVELOPER"
                         }
                     ]
                 },
                 {
                     "id": 6,
                     "empName": "KANTH",
                     "salary": 11111111,
                     "designation": "DEVELOPER"
                 }
             ]
         },
         {
             "id": 3,
             "empName": "KIRAN",
             "salary": 333333,
             "designation": "MANAGER"
         }
     ]
 }

How InOut parameter will work in java?

Objective:
Objective of this article is to explain How references will work in java or How InOut parameter will work in Java?

Explanation:
We studied in C language the importance of  pointers similarly we need to know how references are working in java. Without knowing how object references are working in java, we cant understand application flow properly.

Lets take one example in java related to references as well as InOut parameter in java.

class Student{ 
     private Integer id; 
     private String name; 
     //setter and getter 
 } 
 class Main{ 
     public static void main(String arg…){ 
         Student s1=new Student(); 
         System.out.println(s1.getId()); 
         System.out.println(s1.getName()); 
         m1(s1); 
         System.out.println(s1.getId()); 
         System.out.println(s1.getName()); 
     } 
     public static void m1(Student s3){ 
         s3.setId(10); 
         s3.setName("ranga"); 
         s3=null;
     } 
 }

In the above program we used new keyword only one time so entire program will have only one student object created.

Once we create object s1 is pointing to that object and its id,name values initialize with null values like the below screenshot.

When we execute the below code, it will return with null value.

System.out.println(s1.getId());//null 
System.out.println(s1.getName());//null

When we call m1(s1); then Student s3=s1; then s3 reference also pointing to same object which is already referred by s1 reference. Look at the below image,

When we execute s3.setId(10); and s3.setName(“Ranga”); then s3 reference id value(null) override with 10 and name value(null) override with “Ranga”. Look at the below diagram,

When we do s3=null then it will lost the connection with that reference and m1 method execution is over because it doesn’t return anything because of it’s return type is void. Look at the below diagram,

The below diagram illustrates, that the previously setting s3 values are pointing to s1 because s3 lost connection with them.

Now it we print id and name of s1 reference, it will print id as 10 and name is “Ranga” because s1 is pointing to Student object which has the values of 10 and “Ranga”.

I hope this helped you to understand about references in Java. Let us know your thoughts. Happy Learning 🙂