使用 Stringbuilder 与整数数组的算法性能

Performance of algorithm using Stringbuilder vs Integer array

我正在尝试根据特定条件用 1 和 0 组成一个字符串(长度为 10,000)'valid'。

虽然我能够做到这一点,但我担心性能问题,需要一些帮助来决定以下两种方法中哪一种性能更好。

方法 1(使用 Stringbuilder)

StringBuilder output = new StringBuilder(); 

    for( int i = 0; i < 10000; i++ )
        {
            if ( valid )
            {
                output.append( "1" );
            }
            else
            {
                output.append( "0" );
            }
        }

方法二(使用整型数组)

int[] gridArray = new int[ 10000 ];

   for( int i = 0; i < 10000; i++ )
    {
        if ( valid )
        {
            gridArray[i] = 1;
        }
    }

        //Convert grid array to string output

另外,如何最好将整数数组转换为字符串?

以上

None

最适合你的class是BitSet

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

默认情况下,集合中的所有位最初都具有值 false。

如果你真的想用已知长度的 1s 和 0s 构建一个字符串,那么最有效的方法可能是构建一个字符数组并从中创建一个字符串.沿线的东西:

char[] result = new char[10000];
for (int index = 0; index < result.length; index++) {
    result[index] = (index %2 == 0) ? '1' : '0';
}
String stringResult = new String(result);

StringBuilder(用足够的容量初始化)可能会有相同的性能,所以我实际上接受了它。有一些最小的容量,但它甚至不值得一提。

此处建议的其他结构(整数数组或位集)可能更适合存储您的 10,但它们仍然需要转换为字符串。无论如何,这可能需要 StringBuilder。例如,BitSet 在其 toString() 方法中使用 StringBuilder