How efficient is std::string compared to null-terminated strings?

前端 未结 14 2136
心在旅途
心在旅途 2020-12-28 19:23

I\'ve discovered that std::strings are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall pr

14条回答
  •  心在旅途
    2020-12-28 19:56

    When writing C++ code using any utility class (whether STL or your own) instead of eg. good old C null terminated strings, you need to rememeber a few things.

    • If you benchmark without compiler optimisations on (esp. function inlining), classes will lose. They are not built-ins, even stl. They are implemented in terms of method calls.

    • Do not create unnesessary objects.

    • Do not copy objects if possible.

    • Pass objects as references, not copies, if possible,

    • Use more specialised method and functions and higher level algorithms. Eg.:

      std::string a = "String a"
      std::string b = "String b"
      
      // Use
      a.swap(b);
      
      // Instead of
      std::string tmp = a;
      a = b;
      b = tmp;
      

    And a final note. When your C-like C++ code starts to get more complex, you need to implement more advanced data structures like automatically expanding arrays, dictionaries, efficient priority queues. And suddenly you realise that its a lot of work and your classes are not really faster then stl ones. Just more buggy.

提交回复
热议问题