A T
A T

Reputation: 13836

Efficiently store array of up to 2048 characters?

Getting input from another source; which populates a string of up to 2048 characters.

What is the most efficient way of populating and comparing this string? - I want to be able to easily append to the string also.

Here are three attempts of mine:

C-style version

#include <cstdio>
#include <cstring>

int main(void) {
    char foo[2048];
    foo[0]='a', foo[1]='b', foo[2]='c', foo[3]='\0';  // E.g.: taken from u-input
    puts(strcmp(foo, "bar")? "false": "true");
}

C++-style version 0

#include <iostream>

int main() {
    std::string foo;
    foo.reserve(2048);
    foo += "abc";  // E.g.: taken from user-input
    std::cout << std::boolalpha << (foo=="bar");
}

C++-style version 1

#include <iostream>

int main() {
    std::string foo;
    foo += "abc";  // E.g.: taken from user-input
    std::cout << std::boolalpha << (foo=="bar");
}

Upvotes: 0

Views: 740

Answers (1)

Deduplicator
Deduplicator

Reputation: 45674

What is most efficient depends on what you optimize for.
Some common criteria:

  1. Program Speed
  2. Program Size
  3. Working Set Size
  4. Code Size
  5. Programmer Time
  6. Safety

Undoubted King for 1 and 2, in your example probably also 3, is C style.
For 4 and 5, C++ style 1.
Point 6 is probably with C++-style.

Still, the proper mix of emphasizing these goal is called for, which imho favors C++ option 0.

Upvotes: 1

Related Questions