Hacker News new | past | comments | ask | show | jobs | submit login

Or if say, most strings tend to be small (<256 chars), use 8 unused bits of the pointer for the length. If the string is longer than that, mask the bits to 0. Then the string handling functions can have a fast path that uses the length from pointer if available, if not, walks the entire string.



I think most(?) C++ implementations of std::string use something called a short-string optimization, where the string type is something like

  struct string {
    size_t len;
    union {
        char* ptr_to_malloced_string;
        char short_string[sizeof(char*)];
    }
  }

So if the length of the string is shorter than the size of a pointer, the string is stored inline in the struct, and if the length is longer it's a separate allocated object.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: