NV phone screen
I was asked to implement a high-performance class to handle large strings, with functions like cmp, cat, substr, and so on. I created a simple class that uses a char array to store short strings. First I was asked to write the constructor:
const BUFF_SZIE = 128;
class myString {
private:
char buf[BUFF_SZIE];
size_t length;
char *ptr;
public:
myString(char *s, size_t len) {
length = len;
if (len < BUFF_SZIE) {
strncpy(buf, s, len);
buf[len] = 0;
} else {
ptr = (char *)malloc(len+1);
if (ptr == nullptr) {
throw "not enough memory";
}
memcpy(ptr, s, len);
*(ptr+len) = 0;
}
}
}
- Q: For
strncpy(buf, s, len), characters get copied one at a time — how can this be sped up?
A: Usememcpy. - Q: Is that the same as
strncpy?
A: ? — cast the buffer to integers, which is 4x faster. - Q: For the
cmpfunction, why is comparing short strings (<256 bytes) faster than comparing long strings (ignoring the difference in length)?
A: ? — short strings sit in the CPU cache. - Q: If
BUFF_SZIE == 1, what is the size ofmyString?
A: 12 bytes on a 32-bit machine, 24 bytes on a 64-bit machine. - Q: If
BUFF_SZIE == 8, but the strings are only 10-15 characters, how can the size of the class be reduced?
A: Dropchar *ptrand use the buffer itself to hold the pointer — this needs heap allocation (malloc) — a union can be used.
Discussion
Loading comments…