Previous: Plural forms, Up: gettext   [Contents][Index]


11.2.7 Optimization of the *gettext functions

At this point of the discussion we should talk about an advantage of the GNU gettext implementation. Some readers might have pointed out that an internationalized program might have a poor performance if some string has to be translated in an inner loop. While this is unavoidable when the string varies from one run of the loop to the other it is simply a waste of time when the string is always the same. Take the following example:

{
  while (…)
    {
      puts (gettext ("Hello world"));
    }
}

When the locale selection does not change between two runs the resulting string is always the same. One way to use this is:

{
  str = gettext ("Hello world");
  while (…)
    {
      puts (str);
    }
}

But this solution is not usable in all situation (e.g. when the locale selection changes) nor does it lead to legible code.

For this reason, GNU gettext caches previous translation results. When the same translation is requested twice, with no new message catalogs being loaded in between, gettext will, the second time, find the result through a single cache lookup.