Optimize string (mis)handling (#8128)

* Optimize statbar drawing

The texture name of the statbar is a string passed by value.
That slows down the client and creates litter in the heap
as the content of the string is allocated there. Convert the
offending parameter to a const reference to avoid the
performance hit.

* Optimize texture cache

There is an unnecessary temporary created when the texture
path is being generated. This slows down the cache each time
a new texture is encountered and it needs to be loaded into
the cache. Additionally, the heap litter created by this
unnecessary temporary is particularly troublesome here as
the following code then piles another string (the resulting
full path of the texture) on top of it, followed by the
texture itself, which both are quite long term objects as
they are subsequently inserted into the cache where they can
remain for quite a while (especially if the texture turns
out to be a common one like dirt, grass or stone).

Use std::string.append to get rid of the temporary which
solves both issues (speed and heap fragmentation).

* Optimize animations in client

Each time an animated node is updated, an unnecessary copy of
the texture name is created, littering the heap with lots of
fragments. This can be specifically troublesome when looking
at oceans or large lava lakes as both of these nodes are
usually animated (the lava animation is pretty visible).
Convert the parameter of GenericCAO::updateTextures to a
const reference to get rid of the unnecessary copy.

There is a comment stating "std::string copy is mandatory as
mod can be a class member and there is a swap on those class
members ... do NOT pass by reference", reinforcing the
belief that the unnecessary copy is in fact necessary.
However one of the first things the code of the method does
is to assign the parameter to its class member, creating
another copy. By rearranging the code a little bit this
"another copy" can then be used by the subsequent code,
getting rid of the need to pass the parameter by value and
thus saving that copying effort.

* Optimize chat console history handling

The GUIChatConsole::replaceAndAddToHistory was getting the
line to work on by value which turns out to be unnecessary.
Get rid of that unnecessary copy by converting the parameter
to a const reference.

* Optimize gui texture setting

The code used to set the texture for GUI components was
getting the name of the texture by value, creating
unnecessary performance bottleneck for mods/games with
heavily textured GUIs. Get rid of the bottleneck by passing
the texture name as a const reference.

* Optimize sound playing code in GUIEngine

The GUIEngine's code receives the specification of the sound
to be played by value, which turns out to be most likely a
mistake as the underlying sound manager interface receives
the same thing by reference. Convert the offending parameter
to a const reference to get rid of the rather bulky copying
effort and the associated performance hit.

* Silence CLANG TIDY warnings for unit tests

Change "std::string" to "const std::string &" to avoid an
unnecessary local value copy, silencing the CLANG TIDY
process.

* Optimize formspec handling

The "formspec prepend" parameter was passed to the formspec
handling code by value, creating unnecessary copy of
std::string and slowing down the game if mods add things like
textured backgrounds for the player inventory and/or other
forms. Get rid of that performance bottleneck by converting
the parameter to a const reference.

* Optimize hotbar image handling

The code that sets the background images for the hotbar is
getting the name of the image by value, creating an
unnecessary std::string copying effort. Fix that by
converting the relevant parameters to const references.

* Optimize inventory deserialization

The inventory manager deserialization code gets the
serialized version of the inventory by value, slowing the
server and the client down when there are inventory updates.
This can get particularly troublesome with pipeworks which
adds nodes that can mess around with inventories
automatically or with mods that have mobs with inventories
that actively use them.

* Optimize texture scaling cache

There is an io::path parameter passed by value in the
procedure used to add images converted from textures,
leading to slowdown when the image is not yet created and
the conversion is thus needed. The performance hit is
quite significant as io::path is similar to std::string
so convert the parameter to a const reference to get rid of
it.

* Optimize translation file loader

Use "std::string::append" when calculating the final index
for the translation table to avoid unnecessary temporary
strings. This speeds the translation file loader up
significantly as std::string uses heap allocation which
tends to be rather slow. Additionally, the heap is no
longer being littered by these unnecessary string
temporaries, increasing performance of code that gets
executed after the translation file loader finishes.

* Optimize server map saving

When the directory structure for the world data is created
during server map saving, an unnecessary value passing of
the directory name slows things down. Remove that overhead
by converting the offending parameter to a const reference.
master
Jozef Behran 2019-05-18 10:19:13 -05:00 committed by SmallJoker
parent 568694122c
commit eb2bda7d0b
21 changed files with 41 additions and 28 deletions

View File

@ -1062,7 +1062,7 @@ void GenericCAO::updateTexturePos()
} }
} }
void GenericCAO::updateTextures(std::string mod) void GenericCAO::updateTextures(const std::string &modref)
{ {
ITextureSource *tsrc = m_client->tsrc(); ITextureSource *tsrc = m_client->tsrc();
@ -1071,9 +1071,21 @@ void GenericCAO::updateTextures(std::string mod)
bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter"); bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
m_previous_texture_modifier = m_current_texture_modifier; m_previous_texture_modifier = m_current_texture_modifier;
m_current_texture_modifier = mod; m_current_texture_modifier = modref;
m_glow = m_prop.glow; m_glow = m_prop.glow;
// Create a reference to the copy of "modref" just created. The
// following code will then use this reference instead of the
// original parameter which was passed by reference. This is
// necessary as "modref" can be a class member and there is a swap on
// those class members which can get triggered by the rest of the
// code of this method. This is faster than passing the "mod" by
// value because it reuses the copy made by the assignment to
// m_current_texture_modifier for the "mod" instead of having two
// copies, one for "mod" and another one (created from "mod") for
// the m_current_texture_modifier class member.
const std::string &mod = m_current_texture_modifier;
video::E_MATERIAL_TYPE material_type = (m_prop.use_texture_alpha) ? video::E_MATERIAL_TYPE material_type = (m_prop.use_texture_alpha) ?
video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;

View File

@ -225,9 +225,7 @@ public:
void updateTexturePos(); void updateTexturePos();
// std::string copy is mandatory as mod can be a class member and there is a swap void updateTextures(const std::string &modref);
// on those class members... do NOT pass by reference
void updateTextures(std::string mod);
void updateAnimation(); void updateAnimation();

View File

@ -39,7 +39,7 @@ std::map<io::path, video::ITexture *> g_txrCache;
/* Manually insert an image into the cache, useful to avoid texture-to-image /* Manually insert an image into the cache, useful to avoid texture-to-image
* conversion whenever we can intercept it. * conversion whenever we can intercept it.
*/ */
void guiScalingCache(io::path key, video::IVideoDriver *driver, video::IImage *value) void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value)
{ {
if (!g_settings->getBool("gui_scaling_filter")) if (!g_settings->getBool("gui_scaling_filter"))
return; return;

View File

@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
/* Manually insert an image into the cache, useful to avoid texture-to-image /* Manually insert an image into the cache, useful to avoid texture-to-image
* conversion whenever we can intercept it. * conversion whenever we can intercept it.
*/ */
void guiScalingCache(io::path key, video::IVideoDriver *driver, video::IImage *value); void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value);
// Manually clear the cache, e.g. when switching to different worlds. // Manually clear the cache, e.g. when switching to different worlds.
void guiScalingCacheClear(); void guiScalingCacheClear();

View File

@ -372,7 +372,7 @@ void Hud::drawLuaElements(const v3s16 &camera_offset)
} }
void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, std::string texture, void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture,
s32 count, v2s32 offset, v2s32 size) s32 count, v2s32 offset, v2s32 size)
{ {
const video::SColor color(255, 255, 255, 255); const video::SColor color(255, 255, 255, 255);

View File

@ -81,7 +81,7 @@ public:
void drawLuaElements(const v3s16 &camera_offset); void drawLuaElements(const v3s16 &camera_offset);
private: private:
void drawStatbar(v2s32 pos, u16 corner, u16 drawdir, std::string texture, void drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture,
s32 count, v2s32 offset, v2s32 size = v2s32()); s32 count, v2s32 offset, v2s32 size = v2s32());
void drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, void drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,

View File

@ -131,7 +131,8 @@ std::string getTexturePath(const std::string &filename)
Check from texture_path Check from texture_path
*/ */
for (const auto &path : getTextureDirs()) { for (const auto &path : getTextureDirs()) {
std::string testpath = path + DIR_DELIM + filename; std::string testpath = path + DIR_DELIM;
testpath.append(filename);
// Check all filename extensions. Returns "" if not found. // Check all filename extensions. Returns "" if not found.
fullpath = getImagePath(testpath); fullpath = getImagePath(testpath);
if (!fullpath.empty()) if (!fullpath.empty())

View File

@ -139,7 +139,7 @@ f32 GUIChatConsole::getDesiredHeight() const
return m_desired_height_fraction; return m_desired_height_fraction;
} }
void GUIChatConsole::replaceAndAddToHistory(std::wstring line) void GUIChatConsole::replaceAndAddToHistory(const std::wstring &line)
{ {
ChatPrompt& prompt = m_chat_backend->getPrompt(); ChatPrompt& prompt = m_chat_backend->getPrompt();
prompt.addToHistory(prompt.getLine()); prompt.addToHistory(prompt.getLine());

View File

@ -60,7 +60,7 @@ public:
f32 getDesiredHeight() const; f32 getDesiredHeight() const;
// Replace actual line when adding the actual to the history (if there is any) // Replace actual line when adding the actual to the history (if there is any)
void replaceAndAddToHistory(std::wstring line); void replaceAndAddToHistory(const std::wstring &line);
// Change how the cursor looks // Change how the cursor looks
void setCursor( void setCursor(

View File

@ -518,7 +518,7 @@ void GUIEngine::drawFooter(video::IVideoDriver *driver)
} }
/******************************************************************************/ /******************************************************************************/
bool GUIEngine::setTexture(texture_layer layer, std::string texturepath, bool GUIEngine::setTexture(texture_layer layer, const std::string &texturepath,
bool tile_image, unsigned int minsize) bool tile_image, unsigned int minsize)
{ {
video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IVideoDriver *driver = RenderingEngine::get_video_driver();
@ -593,7 +593,7 @@ void GUIEngine::updateTopLeftTextSize()
} }
/******************************************************************************/ /******************************************************************************/
s32 GUIEngine::playSound(SimpleSoundSpec spec, bool looped) s32 GUIEngine::playSound(const SimpleSoundSpec &spec, bool looped)
{ {
s32 handle = m_sound_manager->playSound(spec, looped); s32 handle = m_sound_manager->playSound(spec, looped);
return handle; return handle;

View File

@ -247,7 +247,7 @@ private:
* @param layer draw layer to specify texture * @param layer draw layer to specify texture
* @param texturepath full path of texture to load * @param texturepath full path of texture to load
*/ */
bool setTexture(texture_layer layer, std::string texturepath, bool setTexture(texture_layer layer, const std::string &texturepath,
bool tile_image, unsigned int minsize); bool tile_image, unsigned int minsize);
/** /**
@ -296,7 +296,7 @@ private:
clouddata m_cloud; clouddata m_cloud;
/** start playing a sound and return handle */ /** start playing a sound and return handle */
s32 playSound(SimpleSoundSpec spec, bool looped); s32 playSound(const SimpleSoundSpec &spec, bool looped);
/** stop playing a sound started with playSound() */ /** stop playing a sound started with playSound() */
void stopSound(s32 handle); void stopSound(s32 handle);

View File

@ -86,7 +86,7 @@ inline u32 clamp_u8(s32 value)
GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst, Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
std::string formspecPrepend, const std::string &formspecPrepend,
bool remap_dbl_click): bool remap_dbl_click):
GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr), GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
m_invmgr(client), m_invmgr(client),

View File

@ -287,7 +287,7 @@ public:
ISimpleTextureSource *tsrc, ISimpleTextureSource *tsrc,
IFormSource* fs_src, IFormSource* fs_src,
TextDest* txt_dst, TextDest* txt_dst,
std::string formspecPrepend, const std::string &formspecPrepend,
bool remap_dbl_click = true); bool remap_dbl_click = true);
~GUIFormSpecMenu(); ~GUIFormSpecMenu();

View File

@ -93,7 +93,7 @@ void InventoryLocation::deSerialize(std::istream &is)
} }
} }
void InventoryLocation::deSerialize(std::string s) void InventoryLocation::deSerialize(const std::string &s)
{ {
std::istringstream is(s, std::ios::binary); std::istringstream is(s, std::ios::binary);
deSerialize(is); deSerialize(is);

View File

@ -97,7 +97,7 @@ struct InventoryLocation
std::string dump() const; std::string dump() const;
void serialize(std::ostream &os) const; void serialize(std::ostream &os) const;
void deSerialize(std::istream &is); void deSerialize(std::istream &is);
void deSerialize(std::string s); void deSerialize(const std::string &s);
}; };
struct InventoryAction; struct InventoryAction;

View File

@ -1717,7 +1717,7 @@ bool ServerMap::loadFromFolders() {
return false; return false;
} }
void ServerMap::createDirs(std::string path) void ServerMap::createDirs(const std::string &path)
{ {
if (!fs::CreateAllDirs(path)) { if (!fs::CreateAllDirs(path)) {
m_dout<<"ServerMap: Failed to create directory " m_dout<<"ServerMap: Failed to create directory "

View File

@ -389,7 +389,7 @@ public:
Misc. helper functions for fiddling with directory and file Misc. helper functions for fiddling with directory and file
names when saving names when saving
*/ */
void createDirs(std::string path); void createDirs(const std::string &path);
// returns something like "map/sectors/xxxxxxxx" // returns something like "map/sectors/xxxxxxxx"
std::string getSectorDir(v2s16 pos, int layout = 2); std::string getSectorDir(v2s16 pos, int layout = 2);
// dirname: final directory name // dirname: final directory name

View File

@ -3207,7 +3207,7 @@ bool Server::hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount)
return true; return true;
} }
void Server::hudSetHotbarImage(RemotePlayer *player, std::string name) void Server::hudSetHotbarImage(RemotePlayer *player, const std::string &name)
{ {
if (!player) if (!player)
return; return;
@ -3216,7 +3216,7 @@ void Server::hudSetHotbarImage(RemotePlayer *player, std::string name)
SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_IMAGE, name); SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_IMAGE, name);
} }
void Server::hudSetHotbarSelectedImage(RemotePlayer *player, std::string name) void Server::hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name)
{ {
if (!player) if (!player)
return; return;

View File

@ -296,8 +296,8 @@ public:
bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value); bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask); bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount); bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
void hudSetHotbarImage(RemotePlayer *player, std::string name); void hudSetHotbarImage(RemotePlayer *player, const std::string &name);
void hudSetHotbarSelectedImage(RemotePlayer *player, std::string name); void hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name);
Address getPeerAddress(session_t peer_id); Address getPeerAddress(session_t peer_id);

View File

@ -149,6 +149,8 @@ void Translations::loadTranslation(const std::string &data)
<< wide_to_utf8(oword1) << "\"" << std::endl; << wide_to_utf8(oword1) << "\"" << std::endl;
} }
m_translations[textdomain + L"|" + oword1] = oword2; std::wstring translation_index = textdomain + L"|";
translation_index.append(oword1);
m_translations[translation_index] = oword2;
} }
} }

View File

@ -152,7 +152,7 @@ void TestAreaStore::testSerialization()
1 + 2 + 1 + 2 +
6 + 6 + 2 + 6 + 6 + 6 + 2 + 6 +
6 + 6 + 2 + 6); 6 + 6 + 2 + 6);
UASSERTEQ(std::string, str, str_wanted); UASSERTEQ(const std::string &, str, str_wanted);
std::istringstream is(str); std::istringstream is(str);
store.deserialize(is); store.deserialize(is);