Android Question String optimization

Alessandro71

Well-Known Member
Licensed User
Longtime User
Having a lot of string building statement, I was asking myself what is the best way to handle that, from a performance and memory handling perspective:

B4X:
newstring = "constant string" & variablestring

or

B4X:
newstring = $"constant string${variablestring}"$

both produce the same result, but which one generates the best code and runtime performance?
 
Solution
I would guess the & version - it produces less java code
B4X:
' &
_newstring1 = "constant string"+_variablestring;
' smartstring
_newstring2 = ("constant string"+anywheresoftware.b4a.keywords.Common.SmartStringFormatter("",(Object)(_variablestring))+"");

Daestrum

Expert
Licensed User
Longtime User
I would guess the & version - it produces less java code
B4X:
' &
_newstring1 = "constant string"+_variablestring;
' smartstring
_newstring2 = ("constant string"+anywheresoftware.b4a.keywords.Common.SmartStringFormatter("",(Object)(_variablestring))+"");
 
Upvote 0
Solution

Sagenut

Expert
Licensed User
Longtime User
Not sure about what I am about to write, but...
Regular string are Immutable.
So trying to modify it will, with a concatenation with & for example, anyway create an additional new string.
To avoid this it should be used the StringBuilder that will manage mutable string and will effectively reuse the same string.
Here the documentation:
https://www.b4x.com/android/help/core.html#stringbuilder
 
Upvote 0

Alessandro71

Well-Known Member
Licensed User
Longtime User
yes, but my use case is not about changing an existing string, rather than creating a new one from exiting ones
 
Upvote 0

emexes

Expert
Licensed User
Having a lot of string building statement
my use case is ... creating a new one from existing ones

Why not StringBuilder? ("especially useful for when you need to concatenate many strings")

1724292317648.png
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
both produce the same result, but which one generates the best code and runtime performance?
The performance difference, if there is one, is negligible = no user will ever feel any difference. Use the one that you feel that is simpler.

If you are building very large strings then you should use StringBuilder.
 
Upvote 0
Top