I was working on Stringbuffer for retrieving current capacity of the buffer and I found very strange behavior.
I am run below code in both Java and Android.
According to many resources I found this formula for increase buffer capacity
If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
sb.append("Hello Hello Hello Hello");
System.out.println(sb.capacity());
System.out.println(sb.length());
Java output--
default capacity = 16
increases capacity = 34
length = 23
Android output--
default capacity = 16
increases capacity = 26
length = 23
I can't understand this, if anyone know about this then Please help me.
Thanks in Advance.
The way the capacity of a StringBuffer gets increased is an internal implementation detail. Its API allows you to look at the capacity to allow your code to make performance-related decisions. The documentation/contract for this class makes no guarantees about exactly how its capacity gets automatically increased. They are therefore allowed to differ on different platforms. What must be the same on both platforms is the length of the string by the StringBuffer.
By the way, you should use StringBuilder instead, if you are not using the same StringBuffer object in multiple threads.
The class definition for StringBuffer doesn't explicitly define any requirements for how much the implementation should increase the capacity by. Different implementations are free to do it however they like.
Given the memory limitation on mobile devices, it would make sense that Android isn't as liberal with the amount of extra space it allocates to the buffer when it needs to increase it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With