R
Roedy Green
I put in a little bit of code like this to see how good I was at
estimating the initial size for StringBuilder size allocation.
I was embarrassed to discover I badly underestimated in every single
case. That meant StringBuilder had to pause in the middle of each
string constructed to double the buffer size, then garbage collect
twice as many objects as it need have done.
You might use this code to check out how good you are at estimating.
/**
* Used to fine tune initial StringBuilder size estimates. Insert
a call to checkEstimate just before toString.
*
* @param sb the StringBuilder to check.
* @param initSize initial size the StringBuilder was allocated.
*/
static void checkEstimate( StringBuilder sb, int initSize )
{
final int size = sb.length();
if ( size > initSize )
{
Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
StackTraceElement e = es[ 1 ];
err.println( "at " + e.getClassName()
+ "." + e.getMethodName()
+ " line:" + e.getLineNumber() );
err.println( "StringBuffer initially sized too small " +
initSize + " to contain " + size + " without autogrowing." );
}
else
{
if ( size + 100 < initSize )
{
Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
StackTraceElement e = es[ 1 ];
err.println( "at " + e.getClassName()
+ "." + e.getMethodName()
+ " line:" + e.getLineNumber() );
err.println( "StringBuffer initially sized needlessly
large " + initSize + " to contain contain " + size );
}
}
}
estimating the initial size for StringBuilder size allocation.
I was embarrassed to discover I badly underestimated in every single
case. That meant StringBuilder had to pause in the middle of each
string constructed to double the buffer size, then garbage collect
twice as many objects as it need have done.
You might use this code to check out how good you are at estimating.
/**
* Used to fine tune initial StringBuilder size estimates. Insert
a call to checkEstimate just before toString.
*
* @param sb the StringBuilder to check.
* @param initSize initial size the StringBuilder was allocated.
*/
static void checkEstimate( StringBuilder sb, int initSize )
{
final int size = sb.length();
if ( size > initSize )
{
Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
StackTraceElement e = es[ 1 ];
err.println( "at " + e.getClassName()
+ "." + e.getMethodName()
+ " line:" + e.getLineNumber() );
err.println( "StringBuffer initially sized too small " +
initSize + " to contain " + size + " without autogrowing." );
}
else
{
if ( size + 100 < initSize )
{
Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
StackTraceElement e = es[ 1 ];
err.println( "at " + e.getClassName()
+ "." + e.getMethodName()
+ " line:" + e.getLineNumber() );
err.println( "StringBuffer initially sized needlessly
large " + initSize + " to contain contain " + size );
}
}
}