search
HomeDatabaseRedisExample analysis of Redis's zmalloc function

Let’s look directly at the custom zmalloc function in the Redis source code (not the latest version). This function is used in exactly the same way as regular functions such as malloc. The difference lies in its internal implementation details.

void *zmalloc(size_t size) {

// Allocate memory;

void *ptr = malloc(size PREFIX_SIZE);

// Allocation failure throws exception;

If (!ptr) zmalloc_oom_handler(size);

// Can the system use the "malloc_size" function?

#ifdef HAVE_MALLOC_SIZE

Update_zmalloc_stat_alloc(zmalloc_size(ptr));

Return ptr;

#else

//Save the actual size of allocated data in the data field;

*((size_t*)ptr) = size;

// Calculate the memory usage after alignment and update the "used_memory" variable;

Update_zmalloc_stat_alloc(size PREFIX_SIZE);

// Return the initial position of the data body;

Return (char*)ptr PREFIX_SIZE;

#endif

}

In fact, the malloc function in the standard library can already automatically align the allocated memory, so the main purpose of the zmalloc method here is to accurately calculate the memory size allocated for each data storage. Each time memory is allocated, zmalloc will add an additional memory space of PREFIX_SIZE size to the allocated data memory size. This PREFIX_SIZE macro represents the maximum memory addressing space size (size_t) of the current system. Varies depending on the type of specific system. Here we can refer to this PREFIX_SIZE size space as the "data header" part of a storage unit.

The storage unit structure of the first version of Redis

As shown in the figure above, through the *((size_t*)ptr) = size; statement, Redis stores the actual allocated data block size in the first PREFIX_SIZE bytes of the currently allocated memory block, that is, in the data header, and in the following Binary data entities are actually stored in the memory space of "size" size. The function named update_zmalloc_stat_alloc here maintains a global variable named used_memory internally, which accumulates the memory size newly allocated each time. The function returns an offset pointer at the end, pointing to the data body part of the currently allocated memory. The specific implementation details of the update_zmalloc_stat_alloc function are as follows.

#define update_zmalloc_stat_alloc(__n) do {

size_t _n = (__n);

// Manual memory completion;

If (_n&(sizeof(long)-1)) _n = sizeof(long)-(_n&(sizeof(long)-1));

atomicIncr(used_memory, __n);

} while(0)

The important thing to note here is the line _n = sizeof(long)-(_n&(sizeof(long)-1));. The entire macro function first determines whether the memory size allocated this time is an integer multiple of sizeof(long) (64-bit machines correspond to 8-byte memory alignment; 32-bit machines correspond to 4-byte memory alignment), if not Then use the statement we gave before to add the corresponding placeholder space after the data segment to make up the number of bits to meet the memory alignment (4/8 bytes) requirements. The final atomicIncr function is used to update the global used_memory variable value while ensuring thread safety.

The process of memory release and memory allocation in this version of Redis is exactly the opposite. The code shown below is the implementation details of the corresponding "zfree" function. First, the function points to the first address of the data field containing the actual size of the data block through the (char*)ptr-PREFIX_SIZE statement (moving to a lower memory address), and then obtains the data through the *((size_t*)realptr) statement. The real memory size allocated by the block (excluding memory alignment areas). Finally, update the value of the global variable used_memory through the update_zmalloc_stat_free function and release the memory segment.

void zfree(void *ptr) {

#ifndef HAVE_MALLOC_SIZE

void *realptr;

size_t oldsize;

#endif

If (ptr == NULL) return;

#ifdef HAVE_MALLOC_SIZE

Update_zmalloc_stat_free(zmalloc_size(ptr));

free(ptr);

#else

realptr = (char*)ptr-PREFIX_SIZE;

Oldsize = *((size_t*)realptr);

Update_zmalloc_stat_free(oldsize PREFIX_SIZE);

free(realptr);

#endif

}

As shown below, if we look at the implementation details of the update_zmalloc_stat_free function, you will find that its execution process is similar to the previous update_zmalloc_stat_alloc function. By calculating the size of memory bytes that need to be supplemented and subtracting the corresponding size of memory space from the used_memory variable, the memory space usage can be accurately calculated.

#define update_zmalloc_stat_free(__n) do { \

size_t _n = (__n); \

If (_n&(sizeof(long)-1)) _n = sizeof(long)-(_n&(sizeof(long)-1)); \

atomicDecr(used_memory,__n); \

} while(0) 

The above is the detailed content of Example analysis of Redis's zmalloc function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),