Advertisement
Ginsutime

How to make strings faster - Most optimized

Feb 14th, 2022
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. static uint32_t s_AllocCount = 0;
  5.  
  6. void* operator new(size_t size)
  7. {
  8.     s_AllocCount++;
  9.     std::cout << "Allocating " << size << " bytes\n";
  10.  
  11.     return malloc(size);
  12. }
  13.  
  14. void PrintName(std::string_view name) // No need for const reference
  15. {
  16.     std::cout << name << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21.     const char* name = "Yan Chernikov"; // Changed from string to const char*
  22.  
  23. #if 0
  24.     std::string firstName = name.substr(0, 3);
  25.     std::string lastName = name.substr(4, 9);
  26. #else
  27.     std::string_view firstName(name, 3); // Removed c_str()
  28.     std::string_view lastName(name + 4, 9); // Removed c_str()
  29. #endif
  30.  
  31.     PrintName("Cherno"); // Also no allocation since PrintName is std::string_view
  32.                         // Changing back to std::string will give an allocation
  33.     PrintName(firstName);
  34.     PrintName(lastName);
  35.  
  36.     std::cout << s_AllocCount << " allocations" << std::endl;
  37.     std::cin.get();
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement