Skip to content

Commit

Permalink
fix performance regression caused by #32
Browse files Browse the repository at this point in the history
the issue isn't with the pr itself, however it did expose the lack of caching with the translation strings, it will
continue to search for strings, even if we already found them.
to solve this, i used a map to cache said strings
  • Loading branch information
ITotalJustice committed Dec 21, 2024
1 parent c8ae2a7 commit d02fbcf
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions sphaira/source/i18n.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,54 @@
#include "log.hpp"
#include <yyjson.h>
#include <vector>
#include <unordered_map>

namespace sphaira::i18n {
namespace {

std::vector<u8> g_i18n_data;
yyjson_doc* json;
yyjson_val* root;
std::unordered_map<std::string, std::string> g_tr_cache;

std::string get_internal(const char* str, size_t len) {
const std::string kkey = {str, len};

if (auto it = g_tr_cache.find(kkey); it != g_tr_cache.end()) {
return it->second;
}

// add default entry
g_tr_cache.emplace(kkey, kkey);

if (!json || !root) {
log_write("no json or root\n");
return str;
return kkey;
}

auto key = yyjson_obj_getn(root, str, len);
if (!key) {
log_write("\tfailed to find key: [%.*s]\n", len, str);
return str;
log_write("\tfailed to find key: [%s]\n", kkey.c_str());
return kkey;
}

auto val = yyjson_get_str(key);
auto val_len = yyjson_get_len(key);
if (!val || !val_len) {
log_write("\tfailed to get value: [%.*s]\n", len, str);
return str;
log_write("\tfailed to get value: [%s]\n", kkey.c_str());
return kkey;
}

return {val, val_len};
// update entry in cache
const std::string ret = {val, val_len};
g_tr_cache.insert_or_assign(kkey, ret);
return ret;
}

} // namespace

bool init(long index) {
g_tr_cache.clear();
R_TRY_RESULT(romfsInit(), false);
ON_SCOPE_EXIT( romfsExit() );

Expand Down

0 comments on commit d02fbcf

Please sign in to comment.