What is an efficient way to compare StringBuilder objects

后端 未结 4 1092
无人共我
无人共我 2021-01-03 19:25

Well I have two StringBuilder objects, I need to compare them in Java. One way I know I can do is

sb1.toString().equals(sb2.toString());

bu

4条回答
  •  盖世英雄少女心
    2021-01-03 20:11

    A solution without new allocations would be to compare first at length, and if it differs, then char by char. This is more efficient and faster than performing a compare via a toString() on the StringBuilder call, which would allocate a new string.

    The next snipped assumes both parameters aren't null neither the same object instance:

    public boolean compare(final StringBuilder left, final StringBuilder right)
    {
        final int length = left.length();
    
        if (length != right.length())
        {
            return false;
        }
    
        for (int index = 0; index < length; index++)
        {
            if (left.charAt(index) != right.charAt(index))
            {
                return false;
            }
        }
    
        return true;
    }
    

提交回复
热议问题