Which is faster between String length() or size() in C++

In this article let’s discuss the size() and length() functions of string class with some examples and at the end, we get to a conclusion regarding both functions.

Ways to calculate the length of a string :

In C++, std:: string is a class that enables us to create string objects which store a sequence of characters(or bytes). Strings end with a terminating null character(‘\0’).

We can calculate the length of the string or we can also say it as we can get the length of the sequence of characters or bytes(where each character is encoded as a byte in C++) in many ways.

  • Using a for/while loop, iterate over the string until we encounter a terminating null character(‘\0’).
  • Using size() inbuilt function
  • Using length() inbuilt function

The length or size of the string is different from the capacity of a string.

Let’s see an example to understand how we generally use the size() function and length() function

size() and length() string function in C++ :

The size() function returns the length of a string. While calculating the length it does not consider the null character at the end of the string.

Syntax : 

str_name.size();

Similarly, the length() function is also used to calculate the length of a string in terms of bytes. This function will return the number of characters in the string, except the terminating null character.

Syntax : 

str_name.length();

Let’s look at the below code to understand how these two functions work.

#include <iostream>
using namespace std;
int main() {
    
    string s = "Codespeedy tutorials";
    int length1 = s.size();
    int length2 = s.length();
    cout<<"length of string using size() function : "<<length1<<"\n";
    cout<<"length of string using length() function : "<<length2<<"\n";
    return 0;
}

Output : 

length of string using size() function : 20
length of string using length() function : 20

In the above code, both functions return the same output. Both functions count the number of characters or bytes. We cannot say one function performed faster than the other, they are equivalent. Both take constant time to calculate the length of a string. We can use the size() function to get the size of other containers like vectors in C++, whereas length() is used only for string objects. We can finally conclude that both size() and length() functions can be used as synonyms. They are the same in functionality and performance also.

Leave a Reply

Your email address will not be published. Required fields are marked *