Current Location: Home> Latest Articles> How to cache the results of mysqli::get_charset to improve efficiency?

How to cache the results of mysqli::get_charset to improve efficiency?

M66 2025-05-18

MySQL extension is a very common tool when using PHP to manipulate MySQL databases. Sometimes we need to call $mysqli->get_charset() to get the character set information used by the current connection.

Although get_charset() itself is not as time consuming as querying a database, it can still bring unnecessary overhead if it is called frequently in high-frequency requests or loops. To optimize performance, we can consider cache the result of get_charset() to avoid repeated calls.

This article will explain how to improve the efficiency of database operations by caching the results of the mysqli::get_charset() function.

What is mysqli::get_charset() ?

The mysqli::get_charset() function returns an object containing the character set information used by the current connection, such as charset , collation , comment , etc.
For example:

 $mysqli = new mysqli('localhost', 'user', 'password', 'database');
$charsetInfo = $mysqli->get_charset();
echo $charsetInfo->charset;  // Output e.g.:utf8mb4

In most cases, we don't need to call it every time, because the character set does not usually change after the connection is established.

Why cache it?

In complex applications, especially in large frameworks or high concurrency scenarios, if the code calls get_charset() once in each database operation, a large number of repeated object creation and function calls will be generated, wasting CPU and memory resources.

With simple caching (e.g. with static variables, global variables, singleton mode), we can get this information only once and then reused throughout the script lifecycle.

Cache implementation example

Here is a simple implementation solution:

 class DatabaseConnection {
    private $mysqli;
    private $charsetInfo = null;

    public function __construct($host, $user, $password, $database) {
        $this->mysqli = new mysqli($host, $user, $password, $database);

        if ($this->mysqli->connect_error) {
            die('Connection failed:' . $this->mysqli->connect_error);
        }
    }

    public function getCharsetInfo() {
        if ($this->charsetInfo === null) {
            $this->charsetInfo = $this->mysqli->get_charset();
        }
        return $this->charsetInfo;
    }

    public function query($sql) {
        return $this->mysqli->query($sql);
    }

    public function close() {
        $this->mysqli->close();
    }
}

// Example of usage
$db = new DatabaseConnection('localhost', 'user', 'password', 'database');

// First call,Will execute get_charset()
$charset = $db->getCharsetInfo();
echo 'Current character set:' . $charset->charset . '<br>';

// Subsequent calls,Use cached values ​​directly
$charsetAgain = $db->getCharsetInfo();
echo 'Get the character set again(cache):' . $charsetAgain->charset . '<br>';

// Perform other queries
$result = $db->query('SELECT * FROM users');
while ($row = $result->fetch_assoc()) {
    echo $row['username'] . '<br>';
}

$db->close();

Benefits of using caching

  1. Reduce function call overhead <br> Reduce the number of times you frequently call get_charset() , especially in loops or high concurrency scenarios.

  2. Improve code maintainability <br> Centrally manage character set information. If you need to expand or modify the cache policy in the future, you only need to modify one place.

  3. Easy to debug and monitor <br> The cache layer can easily add logs, debug output, or cache failure mechanisms.

Advanced optimization suggestions

If your application is distributed or long connections (such as Swoole, Workerman, etc.), it is recommended to extend the cache to the connection pool or global manager.

For example, you can cache connection configurations with APCu, Memcached, or Redis, and share across processes when needed, further reducing initialization costs.

At the same time, note: In multi-threaded or multi-process scenarios, the cache of static variables and object attributes is only valid in the current process, and the strategy needs to be adjusted in combination with the application architecture.