2

I am currently creating my own string class in C++ (mainly for learning reasons). For my question the important part of my string class breaks down to this:

class String {
private:
    wchar_t *m_data = nullptr;
    size_t m_length = 0;

    void initializeFromWCharArr(const wchar_t *data) {
        if (m_length == 0) {
            m_length = wcslen(data);
        }
        m_data = new wchar_t[m_length + 1];
        wmemcpy(m_data, data, m_length + 1);
    }

public:
    String(const wchar_t *data) {
        initializeFromWCharArr(data);
    }
}

Once I was done I made a little benchmark test which created a std::string and my own String 10.000.000 times. std::string is much slower than my version in debug mode. However in release mode std::string is 4 times faster. What does std::string do to achieve such speeds?

The benchmark code looks like this:

    void stringSpeed() {
        while (true) {
            CPUWatch allocationWatch;
            for (int i = 0; i < 10000000; i++) {
                //std::wstring test(L"Hallo!");
                MyString test(L"Hallo!");
            }
            std::cout << allocationWatch.getTimeExpiredSeconds() << std::endl;
        }
    }

CPUWatch is a little helper class that I wrote. It uses std::clock() internally.

I already looked at the implementation of std::string and it also uses wmemcpy and wcslen.

Brotcrunsher
  • 1,964
  • 10
  • 32

0 Answers0