Search code examples
javastringstringbuilder

Time complexity of StringBuilder length() method


What is the time complexity of length() method from StringBuilder class?

String str = "hello";
StringBuilder sb = new StringBuilder(str);

System.out.println(sb.length()); // should print 5

My assumption is O(n) where n is number of characters in the string, similar to length() from String class.


Solution

  • This is a member variable in StringBuilder class:

    /**
     * The count is the number of characters used.
     */
    int count;
    

    And this is the code of length():

    /**
     * Returns the length (character count).
     *
     * @return  the length of the sequence of characters currently
     *          represented by this object
     */
    @Override
    public int length() {
        return count;
    }
    

    What do you think?