Minor code refactor aimed at optimization code (#17055)

* Add const ref, remove excess .c_str(), push_* -> emplace_* and rewrite constructors

* Using std::move(), correct clear strings, better use '= default;', modernize make_* and replace heavy strlen

* Fix: Main thread can reallocate data of worker threads

Co-authored-by: Hielke Morsink <hielke.morsink@gmail.com>
This commit is contained in:
Michael SteenbeekandHielke Morsink authored and GitHub committed 2022-05-07 20:18:09 +02:00
commit 29d123b79d
36 files changed
+76 -85

No files matched your search

+1 -1
View File
@@ -224,7 +224,7 @@ void InGameConsole::WriteLine(const std::string& input, FormatToken colourFormat
{
splitPos = input.find('\n', stringOffset);
line = input.substr(stringOffset, splitPos - stringOffset);
_consoleLines.push_back(colourCodepoint + line);
_consoleLines.emplace_back(colourCodepoint + line);
stringOffset = splitPos + 1;
}
@@ -85,7 +85,7 @@ public:
}
auto seqItem = TitleSequenceManager::GetItem(titleSequenceId);
auto sequence = LoadTitleSequence(seqItem->Path.c_str());
auto sequence = LoadTitleSequence(seqItem->Path);
if (sequence == nullptr)
{
return false;
@@ -418,7 +418,6 @@ private:
}
else
{
std::string extension = Path::GetExtension(hintPath);
bool isScenario = ParkImporter::ExtensionIsScenario(hintPath);
auto parkImporter = ParkImporter::Create(hintPath);
auto result = parkImporter->LoadFromStream(stream, isScenario);
+1 -1
View File
@@ -289,7 +289,7 @@ private:
{
std::string::size_type pos = 0;
std::string::size_type prev = 0;
while ((pos = text.find("\n", prev)) != std::string::npos)
while ((pos = text.find('\n', prev)) != std::string::npos)
{
_changelogLines.push_back(text.substr(prev, pos - prev));
prev = pos + 1;
@@ -1378,7 +1378,7 @@ private:
void FilterUpdateCounts()
{
if (!_FILTER_ALL || strlen(_filter_string) > 0)
if (!_FILTER_ALL || _filter_string[0] != '\0')
{
const auto& selectionFlags = _objectSelectionFlags;
std::fill(std::begin(_filter_object_counts), std::end(_filter_object_counts), 0);
+2 -2
View File
@@ -901,7 +901,7 @@ static void WindowLoadsavePopulateList(
LoadSaveListItem newListItem;
newListItem.path = Path::Combine(absoluteDirectory, subDir);
newListItem.name = subDir;
newListItem.name = std::move(subDir);
newListItem.type = TYPE_DIRECTORY;
newListItem.loaded = false;
@@ -926,7 +926,7 @@ static void WindowLoadsavePopulateList(
newListItem.time_formatted = Platform::FormatTime(newListItem.date_modified);
// Mark if file is the currently loaded game
newListItem.loaded = newListItem.path.compare(gCurrentLoadedPath.c_str()) == 0;
newListItem.loaded = newListItem.path.compare(gCurrentLoadedPath) == 0;
// Remove the extension (but only the first extension token)
if (!showExtension)
+3 -3
View File
@@ -315,12 +315,12 @@ static void WindowServerListTextinput(rct_window* w, rct_widgetindex widgetIndex
return;
std::fill_n(_playerName, sizeof(_playerName), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_playerName, text, sizeof(_playerName));
}
if (strlen(_playerName) > 0)
if (_playerName[0] != '\0')
{
gConfigNetwork.player_name = _playerName;
config_save_default();
@@ -518,7 +518,7 @@ static void JoinServer(std::string address)
address = address.substr(beginBracketIndex + 1, endBracketIndex - beginBracketIndex - 1);
}
if (!network_begin_client(address.c_str(), port))
if (!network_begin_client(address, port))
{
context_show_error(STR_UNABLE_TO_CONNECT_TO_SERVER, STR_NONE, {});
}
+10 -10
View File
@@ -131,7 +131,7 @@ static void WindowServerStartScenarioselectCallback(const utf8* path)
game_notify_map_change();
if (GetContext()->LoadParkFromFile(path, false, true))
{
network_begin_server(gConfigNetwork.default_port, gConfigNetwork.listen_address.c_str());
network_begin_server(gConfigNetwork.default_port, gConfigNetwork.listen_address);
}
}
@@ -141,7 +141,7 @@ static void WindowServerStartLoadsaveCallback(int32_t result, const utf8* path)
{
game_notify_map_change();
context_load_park_from_file(path);
network_begin_server(gConfigNetwork.default_port, gConfigNetwork.listen_address.c_str());
network_begin_server(gConfigNetwork.default_port, gConfigNetwork.listen_address);
}
}
@@ -226,7 +226,7 @@ static void WindowServerStartTextinput(rct_window* w, rct_widgetindex widgetInde
return;
std::fill_n(_port, sizeof(_port), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_port, text, sizeof(_port));
}
@@ -241,12 +241,12 @@ static void WindowServerStartTextinput(rct_window* w, rct_widgetindex widgetInde
return;
std::fill_n(_name, sizeof(_name), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_name, text, sizeof(_name));
}
if (strlen(_name) > 0)
if (_name[0] != '\0')
{
gConfigNetwork.server_name = _name;
config_save_default();
@@ -259,12 +259,12 @@ static void WindowServerStartTextinput(rct_window* w, rct_widgetindex widgetInde
return;
std::fill_n(_description, sizeof(_description), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_description, text, sizeof(_description));
}
if (strlen(_description) > 0)
if (_description[0] != '\0')
{
gConfigNetwork.server_description = _description;
config_save_default();
@@ -277,12 +277,12 @@ static void WindowServerStartTextinput(rct_window* w, rct_widgetindex widgetInde
return;
std::fill_n(_greeting, sizeof(_greeting), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_greeting, text, sizeof(_greeting));
}
if (strlen(_greeting) > 0)
if (_greeting[0] != '\0')
{
gConfigNetwork.server_greeting = _greeting;
config_save_default();
@@ -295,7 +295,7 @@ static void WindowServerStartTextinput(rct_window* w, rct_widgetindex widgetInde
return;
std::fill_n(_password, sizeof(_password), 0x00);
if (strlen(text) > 0)
if (text[0] != '\0')
{
safe_strcpy(_password, text, sizeof(_password));
}
+3 -3
View File
@@ -5,10 +5,10 @@
namespace GameActions
{
Result::Result(GameActions::Status error, rct_string_id title, rct_string_id message, uint8_t* args /*= nullptr*/)
: Error(error)
, ErrorTitle(title)
, ErrorMessage(message)
{
Error = error;
ErrorTitle = title;
ErrorMessage = message;
if (args != nullptr)
{
std::copy_n(args, ErrorMessageArgs.size(), ErrorMessageArgs.begin());
+1 -1
View File
@@ -122,7 +122,7 @@ GameActions::Result WaterLowerAction::QueryExecute(bool isExecuting) const
return res;
}
uint8_t WaterLowerAction::GetLowestHeight(MapRange validRange) const
uint8_t WaterLowerAction::GetLowestHeight(const MapRange& validRange) const
{
// The lowest height to lower the water to is the highest water level in the selection
uint8_t minHeight{ 0 };
+1 -1
View File
@@ -28,5 +28,5 @@ public:
private:
GameActions::Result QueryExecute(bool isExecuting) const;
uint8_t GetLowestHeight(MapRange validRange) const;
uint8_t GetLowestHeight(const MapRange& validRange) const;
};
+1 -1
View File
@@ -128,7 +128,7 @@ GameActions::Result WaterRaiseAction::QueryExecute(bool isExecuting) const
return res;
}
uint16_t WaterRaiseAction::GetHighestHeight(MapRange validRange) const
uint16_t WaterRaiseAction::GetHighestHeight(const MapRange& validRange) const
{
// The highest height to raise the water to is the lowest water level in the selection
uint16_t maxHeight = 255 * COORDS_Z_STEP;
+1 -1
View File
@@ -28,5 +28,5 @@ public:
private:
GameActions::Result QueryExecute(bool isExecuting) const;
uint16_t GetHighestHeight(MapRange validRange) const;
uint16_t GetHighestHeight(const MapRange& validRange) const;
};
+2 -2
View File
@@ -64,7 +64,7 @@ static exitcode_t HandleUriJoin(const std::vector<std::string>& args)
{
// Set the network start configuration
gNetworkStart = NETWORK_MODE_CLIENT;
gNetworkStartHost = hostname;
gNetworkStartHost = std::move(hostname);
gNetworkStartPort = port;
return EXITCODE_CONTINUE;
}
@@ -88,7 +88,7 @@ static bool TryParseHostnamePort(
port = std::stoi(hostnamePort.substr(colonIndex + 1));
}
*outPort = port;
*outHostname = hostname;
*outHostname = std::move(hostname);
return true;
}
catch (const std::exception&)
+2 -2
View File
@@ -405,7 +405,7 @@ namespace Config
playerName = String::Trim(playerName);
auto model = &gConfigNetwork;
model->player_name = playerName;
model->player_name = std::move(playerName);
model->default_port = reader->GetInt32("default_port", NETWORK_DEFAULT_PORT);
model->listen_address = reader->GetString("listen_address", "");
model->default_password = reader->GetString("default_password", "");
@@ -739,7 +739,7 @@ namespace Config
desc.Filters.emplace_back(language_get_string(STR_ALL_FILES), "*");
const auto userHomePath = Platform::GetFolderPath(SPECIAL_FOLDER::USER_HOME);
desc.InitialDirectory = userHomePath.c_str();
desc.InitialDirectory = userHomePath;
return ContextOpenCommonFileDialog(installerPath, desc, 4096);
}
+2 -2
View File
@@ -287,7 +287,7 @@ private:
}
}
void ParseSectionValues(LineRange range)
void ParseSectionValues(const LineRange& range)
{
for (size_t i = range.Start + 1; i <= range.End; i++)
{
@@ -313,7 +313,7 @@ private:
value = UnquoteValue(value);
value = UnescapeValue(value);
_values[key] = value;
_values[key] = std::move(value);
}
std::string TrimComment(const std::string& s)
+1 -1
View File
@@ -164,7 +164,7 @@ template<> struct DataSerializerTraits_t<std::string>
len = ByteSwapBE(len);
if (len == 0)
{
res = "";
res.clear();
return;
}
auto str = stream->ReadArray<char>(len);
+1 -1
View File
@@ -90,7 +90,7 @@ namespace Http
{
auto key = String::ToUtf8(wKey);
auto value = String::ToUtf8(wValue);
headers[key] = value;
headers[key] = std::move(value);
}
wKey.clear();
wValue.clear();
+1 -3
View File
@@ -37,9 +37,7 @@ struct TextPaint
TextUnderline UnderlineText = TextUnderline::Off;
TextAlignment Alignment = TextAlignment::LEFT;
TextPaint()
{
}
TextPaint() = default;
TextPaint(colour_t colour)
: Colour(colour)
{
+2 -2
View File
@@ -114,7 +114,7 @@ void chat_draw(rct_drawpixelinfo* dpi, uint8_t chatBackgroundColor)
for (int32_t i = 0; i < CHAT_HISTORY_SIZE; i++)
{
if (strlen(chat_history_get(i)) == 0)
if (chat_history_get(i)[0] == '\0')
{
continue;
}
@@ -238,7 +238,7 @@ void chat_input(ChatInput input)
switch (input)
{
case ChatInput::Send:
if (strlen(_chatCurrentLine) > 0)
if (_chatCurrentLine[0] != '\0')
{
network_send_chat(_chatCurrentLine);
}
+3 -3
View File
@@ -114,7 +114,7 @@ public:
}
// Clean up the parsing work data
_currentGroup = std::string();
_currentGroup.clear();
_currentObjectOverride = nullptr;
_currentScenarioOverride = nullptr;
}
@@ -133,7 +133,7 @@ public:
{
if (_strings.size() > static_cast<size_t>(stringId))
{
_strings[stringId] = std::string();
_strings[stringId].clear();
}
}
@@ -566,7 +566,7 @@ private:
}
else
{
_currentScenarioOverride->strings[stringId] = s;
_currentScenarioOverride->strings[stringId] = std::move(s);
}
}
}
@@ -37,9 +37,7 @@ LocalisationService::LocalisationService(const std::shared_ptr<IPlatformEnvironm
}
// Define implementation here to avoid including LanguagePack.h in header
LocalisationService::~LocalisationService()
{
}
LocalisationService::~LocalisationService() = default;
const char* LocalisationService::GetString(rct_string_id id) const
{
+6 -6
View File
@@ -154,12 +154,12 @@ bool NetworkBase::Init()
{
status = NETWORK_STATUS_READY;
ServerName = std::string();
ServerDescription = std::string();
ServerGreeting = std::string();
ServerProviderName = std::string();
ServerProviderEmail = std::string();
ServerProviderWebsite = std::string();
ServerName.clear();
ServerDescription.clear();
ServerGreeting.clear();
ServerProviderName.clear();
ServerProviderEmail.clear();
ServerProviderWebsite.clear();
return true;
}
+2 -6
View File
@@ -17,12 +17,8 @@
# include <vector>
NetworkKey::NetworkKey()
{
}
NetworkKey::~NetworkKey()
{
}
NetworkKey::NetworkKey() = default;
NetworkKey::~NetworkKey() = default;
void NetworkKey::Unload()
{
+2 -2
View File
@@ -174,7 +174,7 @@ std::vector<ServerListEntry> ServerList::ReadFavourites() const
serverInfo.Name = fs.ReadStdString();
serverInfo.RequiresPassword = false;
serverInfo.Description = fs.ReadStdString();
serverInfo.Version = "";
serverInfo.Version.clear();
serverInfo.Favourite = true;
serverInfo.Players = 0;
serverInfo.MaxPlayers = 0;
@@ -340,7 +340,7 @@ std::future<std::vector<ServerListEntry>> ServerList::FetchOnlineServerListAsync
}
Http::Request request;
request.url = masterServerUrl;
request.url = std::move(masterServerUrl);
request.method = Http::Method::GET;
request.header["Accept"] = "application/json";
Http::DoAsync(request, [p](Http::Response& response) -> void {
+10 -10
View File
@@ -257,6 +257,14 @@ private:
public:
TcpSocket() noexcept = default;
explicit TcpSocket(SOCKET socket, std::string hostName, std::string ipAddress) noexcept
: _status(SocketStatus::Connected)
, _socket(socket)
, _ipAddress(std::move(ipAddress))
, _hostName(std::move(hostName))
{
}
~TcpSocket() override
{
if (_connectFuture.valid())
@@ -388,11 +396,11 @@ public:
if (rc == 0)
{
tcpSocket = std::unique_ptr<ITcpSocket>(new TcpSocket(socket, hostName, ipAddress));
tcpSocket = std::make_unique<TcpSocket>(socket, hostName, ipAddress);
}
else
{
tcpSocket = std::unique_ptr<ITcpSocket>(new TcpSocket(socket, "", ipAddress));
tcpSocket = std::make_unique<TcpSocket>(socket, "", ipAddress);
}
}
}
@@ -622,14 +630,6 @@ public:
}
private:
explicit TcpSocket(SOCKET socket, std::string hostName, std::string ipAddress) noexcept
: _status(SocketStatus::Connected)
, _socket(socket)
, _ipAddress(std::move(ipAddress))
, _hostName(std::move(hostName))
{
}
void CloseSocket()
{
if (_socket != INVALID_SOCKET)
+1 -1
View File
@@ -67,7 +67,7 @@ void StringTable::Read(IReadObjectContext* context, OpenRCT2::IStream* stream, O
StringTableEntry entry{};
entry.Id = id;
entry.LanguageId = languageId;
entry.Text = stringAsUtf8;
entry.Text = std::move(stringAsUtf8);
_strings.push_back(std::move(entry));
}
}
+1 -1
View File
@@ -1810,7 +1810,7 @@ namespace OpenRCT2
}
else
{
value = "";
value.clear();
}
}
}
+4 -4
View File
@@ -2105,12 +2105,12 @@ namespace RCT1
std::string userString = GetUserString(_s4.park_name_string_index);
if (!userString.empty())
{
parkName = userString;
parkName = std::move(userString);
}
}
auto& park = GetContext()->GetGameState()->GetPark();
park.Name = parkName;
park.Name = std::move(parkName);
}
void ImportParkFlags()
@@ -2313,8 +2313,8 @@ namespace RCT1
}
}
gScenarioName = name;
gScenarioDetails = details;
gScenarioName = std::move(name);
gScenarioDetails = std::move(details);
}
void ImportScenarioObjective()
+1 -1
View File
@@ -250,7 +250,7 @@ public:
item->Name = newName;
item->Path = newPath;
SortItems();
result = newPath;
result = std::move(newPath);
}
}
}
+2 -2
View File
@@ -457,7 +457,7 @@ void ScriptEngine::RefreshPlugins()
{
if (plugin->HasPath())
{
plugins.push_back(std::string(plugin->GetPath()));
plugins.emplace_back(plugin->GetPath());
}
}
@@ -580,7 +580,7 @@ void ScriptEngine::StopUnloadRegisterAllPlugins()
std::vector<std::string> pluginPaths;
for (auto& plugin : _plugins)
{
pluginPaths.push_back(std::string(plugin->GetPath()));
pluginPaths.emplace_back(plugin->GetPath());
StopPlugin(plugin);
}
for (auto& plugin : _plugins)
+1 -1
View File
@@ -79,7 +79,7 @@ namespace OpenRCT2::Scripting
_backupPlugin = _execInfo._plugin;
_backupIsGameStateMutable = _execInfo._isGameStateMutable;
_execInfo._plugin = plugin;
_execInfo._plugin = std::move(plugin);
_execInfo._isGameStateMutable = isGameStateMutable;
}
PluginScope(const PluginScope&) = delete;
@@ -113,7 +113,7 @@ namespace OpenRCT2::Scripting
}
else
{
store = subStore;
store = std::move(subStore);
}
end = remainder.empty();
} while (!end);
@@ -80,7 +80,7 @@ namespace OpenRCT2::Scripting
auto ride = GetRide();
if (ride != nullptr)
{
ride->custom_name = value;
ride->custom_name = std::move(value);
}
}
@@ -272,7 +272,7 @@ namespace OpenRCT2::Scripting
auto& park = GetContext()->GetGameState()->GetPark();
if (park.Name != value)
{
park.Name = value;
park.Name = std::move(value);
gfx_invalidate_screen();
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ void TitleScreen::Load()
gScreenFlags = SCREEN_FLAGS_TITLE_DEMO;
gScreenAge = 0;
gCurrentLoadedPath = "";
gCurrentLoadedPath.clear();
#ifndef DISABLE_NETWORK
GetContext()->GetNetwork().Close();
+1 -1
View File
@@ -303,7 +303,7 @@ void Park::Initialise()
finance_reset_history();
award_reset();
gScenarioName = "";
gScenarioName.clear();
gScenarioDetails = String::ToStd(language_get_string(STR_NO_DETAILS_YET));
}