I have a category hierarchy like A->B->C-D with at max 4 levels,In this code I have a leaf category for which I need to get the pipe separated names of category hierarchy from root to leaf like A|B|C|D. I have two approaches which will be best from performance and garbage collection point of view?

Approach#1

```
String names = category.getName();
Category parentCategory = category.getParent();
while(parentCategory.getParent() !=null){
   names = parentcategory.getName() + "|" + names;
   parentCategory = parentCategory.getParent();
}

```

Approach#2

```
Deque<String> stack = new ArrayDeque<>();
stack.push(category.getName());
Category parentCategory = category.getParent();
while(parentCategory.getParent() !=null){
   stack.push(parentCategory.getName())
   parentCategory = parentCategory.getParent();
}
String name = String.join("|", stack);

```

As I understand in approach#1 a lot of temporary string objects will be created but will be fast, In approach#2 there will be an additional loop for joining the strings.

Please suggest me with the best way if there I can apply besides above 2.