Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opertion performance between ArrayList or single String

Performance wise, is it better to use ArrayLists to store a list of values, or a String (using concat/+)? Intuitively, I think Strings would perform better since it'd likely use less overhead than ArrayLists but I haven't been able to find anything online.

Also, the entries wouldn't be anything too large (~10).

like image 600
StaticCrazee Avatar asked Apr 12 '26 12:04

StaticCrazee


1 Answers

ArrayList operations

You can get a value from an ArrayList in O(1) and add a value in O(1). Furthermore, ArrayList has already build-in operations that help you to retrieve and add elements.

String operations

Concatenation: With a concat and slice operations, it will be worst. A String is roughly speaking arrays of characters. For example, "Hello" + "Stack" can be represented as array ['H', 'e', 'l', 'l', 'o'] and array ['S', 't', 'a', 'c', 'k']. Now, if you want to concat these two String, you will have to combined all elements of both arrays. It will give you an array of length 10. Therefore, the concatenation - or creating your new char array - is operation in O(n + m).

Worst, if you are concatening n String, you will have a complexity of O(n^2).

Splitting: the complexity of splitting a String is usually O(N) or more. It depends on the regex you will give for the split-operation.

Operations with String are often not that readable and can be stricky to debug.

Long story short

An ArrayList is usually better than operation with String. But all depend on your use case.

like image 70
KeyMaker00 Avatar answered Apr 14 '26 02:04

KeyMaker00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!