Skip to content

Optimizations #19

@ii14

Description

@ii14

Hey, just watched your youtube video. Some recommendations:

  • Enable compiler optimizations with -O2 or -O3!
  • If you won't ship the compiled executable anywhere and you don't need it to be portable (this matters on x86), you can also add -march=native which will optimize the executable to your specific CPU (eg. use extra instructions you have available).
  • threadWorks::sendRequest takes std::string payload by value, which means the string is copied every time. Push std::transform back to threadWorks::runWorkerThread since it only has to happen once, and change the parameter type to const std::string& payload.
  • You're making comparisons like payload == "ocean". This could be a problem, because the right-hand side is a null-terminated string, and at runtime it has to traverse the string to find the null byte to determine the string length (unless it's optimized out by the compiler). You can fix it by including <string_view>, adding using namespace std::string_view_literals;, and replacing such comparisons with payload == "ocean"sv, which will ensure that the string size is known at compile time.
  • You can ditch nlohmann library for generating JSON, and you can simply render it manually to a string. The JSON library will model the structure as nested dynamic data structures (std::string, std::vector, std::unordered_map), which only creates a lot of unnecessary overhead. In the general case there are some things that have to be handled (eg. escaping quotes in strings). But in your case with only integers and alphanumeric strings, you can just do it.
  • oceanBuilder::getRandomFromJson has to parse static JSON on every request, copy it to a vector, and then picks a random entry. Either change the source data to std::vector<std::string>, or push back this work to the main function. Same goes for matchBuilder and myRandom::getRandomVectorFromJSON calls.
  • Since this data will never be modified, you can also change the return type to const std::string* to avoid making copies. Be careful with this though, because there is no reference counting here -- if that string gets deleted (eg. it was local to the function and it goes out of scope), the reference becomes invalid. Enable compiler warnings (-Wall -Wextra) to warn you about mistakes like this.
  • apiClient::sendGETRequest creates requestCombined dynamically. This work can be pushed back too.

To summarize, avoid making allocations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions