What are the techniques for memory allocation and usage statistics of Redis?
Specifically:
If Google’s TC_MALLOC library exists in the system, use the tc_malloc family of functions instead of the original malloc family of functions.
If the current system is a Mac system, use the memory allocation function.
In other cases, an additional fixed-length field is allocated at the beginning of each allocated space to record the allocated space size.
The source codes are in config.h and zmalloc.c respectively:
/* config.h */
#if defined(USE_TCMALLOC)
#include
#if TC_VERSION_MAJOR >= 1 && TC_VERSION_MINOR >= 6
#define HAVE_MALLOC_SIZE 1
#define redis_malloc_size(p) tc_malloc_size(p)
#endif
#elif defined(__APPLE__)
#include
#define HAVE_MALLOC_SIZE 1
#define redis_malloc_size(p) malloc_size(p )
#endif
/* zmalloc.c */
#ifdef HAVE_MALLOC_SIZE
#define PREFIX_SIZE (0)
# else
#if defined(__sun)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t ))
#endif
#endif
Because tc_malloc and the malloc function family under the Mac platform provide functions for calculating the size of allocated space (tc_malloc_size and malloc_size respectively) , so there is no need to allocate a separate space to record the size. For Linux and Sun platforms, the size of the allocated space must be recorded. For linux, use sizeof(size_t) fixed-length field record; for sun os, use sizeof(long long) fixed-length field record. That is the PREFIX_SIZE macro in the source code above.
Re-express this sentence: The purpose of this record is to calculate how much memory is occupied by the current process. In zmalloc.c, there is such a static variable:
static size_t used_memory = 0;
It records the total amount of memory currently occupied by the process. Whenever memory is allocated or released, this variable must be updated. Because when allocating memory, you can clearly know how much memory to allocate. But when releasing memory, (for platforms that do not provide the malloc_size function) you cannot know how much space is released just by pointing to the pointer to the memory to be released. In this case, the fixed-length field specified by PREFIX_SIZE comes into play, and the size of the space can be obtained from the information recorded in it. The zmalloc function is as follows (removing irrelevant code):
void *zmalloc(size_t size) {
void *ptr = malloc(size PREFIX_SIZE);
if (!ptr) zmalloc_oom(size);
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size PREFIX_SIZE,size);
return (char*)ptr PREFIX_SIZE;
. When running on a Mac system or using tc_malloc, the value of PREFIX_SIZE is zero. Next, the first size_t bytes of the memory block pointed to by the pointer ptr will be used to record the allocated size of the memory block. The last thing returned is the pointer beyond the record area. The zfree function is similar (removing irrelevant code):
void zfree(void *ptr) {
void *realptr;
size_t oldsize;
if ( ptr == NULL) return;
realptr = (char*)ptr-PREFIX_SIZE;
oldsize = *((size_t*)realptr);
update_zmalloc_stat_free(oldsize PREFIX_SIZE );
free(realptr);
#endif
}
First move the pointer forward PREFIX_SIZE, and then take out the space saved when allocating space length. Finally, free the entire space.
The two macros update_zmalloc_stat_alloc(__n,__size) and update_zmalloc_stat_free(__n) are responsible for updating the used_memory variable when allocating or releasing memory. Defining it as a macro is mainly due to efficiency considerations. Restore it to a function, as follows:
void update_zmalloc_stat_alloc(__n,__size)
{
do {
size_t _n = (__n );
size_t _stat_slot = (__size ZMALLOC_MAX_ALLOC_STAT) return 0;
Return zmalloc_allocations[size];
}
Another memory usage statistics is returned by calling the zmalloc_used_memory function:
Size_t zmalloc_used_memory(void) {
size_t um;
if (zmalloc_thread_safe) pthread_mutex_lock(&used_memory_mutex);
um = used_memory;
if (zmalloc_thread_safe) pthread_mutex_unlock(&used_memory_mutex);
return um;
}
In addition, zmalloc.c also implements the zmalloc_get_rss function for different systems. In linux In the system, system statistics of memory usage are obtained by reading the /proc/$pid/stat file.
The above is the detailed content of What are the techniques for memory allocation and usage statistics of Redis?. For more information, please follow other related articles on the PHP Chinese website!

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools