pika icon indicating copy to clipboard operation
pika copied to clipboard

refactor:Command objects use memory pools

Open lqxhub opened this issue 1 year ago • 4 comments

优化命令对象, 使用内存池管理命令对象 避免每次执行命令都需要复制一个命令,

Summary by CodeRabbit

  • New Features

    • Introduced a MemoryPool class for efficient memory management.
    • Added new Clone methods across various command classes to utilize the memory pool for object allocation.
    • New methods in PikaCmdTableManager for retrieving raw commands and calculating maximum command size.
  • Bug Fixes

    • Adjusted parameter types in several methods to improve memory management and ownership semantics.
  • Documentation

    • Enhanced error handling and logging in the ACL system.
  • Chores

    • Updated constructor signatures across multiple classes to include memory pool parameters.

lqxhub avatar Dec 17 '24 12:12 lqxhub

Walkthrough

The pull request introduces a comprehensive overhaul of memory management and command handling across the Pika database system. The primary changes involve transitioning from shared pointers to raw pointers for command objects, adding memory pool support, and modifying method signatures to accommodate more flexible memory allocation strategies. These modifications span multiple header and source files, affecting command processing, consensus logging, and thread dispatching mechanisms.

Changes

File/Component Change Summary
include/acl.h Updated method signatures in AclSelector and User classes to use Cmd* instead of std::shared_ptr<Cmd>&.
include/pika_acl.h Added overloaded Clone(net::MemoryPool* pool) method to PikaAclCmd.
include/pika_admin.h Added overloaded Clone(net::MemoryPool* pool) to multiple command classes.
include/pika_bit.h Added Clone(net::MemoryPool* pool) to BitGetCmd, BitSetCmd, etc., and updated Clear methods in some classes.
include/pika_client_conn.h Updated DoCmd return type to std::variant<std::shared_ptr<Cmd>, Cmd*> and added SetMemoryPool method.
include/pika_cmd_table_manager.h Added GetRawCmd(const std::string& opt) and GetMaxCmdSize() methods.
include/pika_command.h Updated Clone method in Cmd class to accept net::MemoryPool*.
include/pika_consensus.h Updated method signatures in ConsensusCoordinator to use Cmd*.
include/pika_dispatch_thread.h Updated constructor to include size_t memory_pool_page_size.
include/pika_geo.h Added Clone(net::MemoryPool* pool) to several geo command classes.
include/pika_hash.h Added Clone(net::MemoryPool* pool) to multiple hash command classes.
include/pika_hyperloglog.h Added Clone(net::MemoryPool* pool) to PfAddCmd, PfCountCmd, and PfMergeCmd.
include/pika_kv.h Added Clone(net::MemoryPool* pool) to numerous KV command classes.
include/pika_list.h Added Clone(net::MemoryPool* pool) to multiple list command classes.
include/pika_pubsub.h Added Clone(net::MemoryPool* pool) to pub/sub command classes and changed member visibility.
include/pika_rm.h Updated ConsensusProposeLog method to accept Cmd*.
include/pika_set.h Added Clone(net::MemoryPool* pool) to various set command classes.
include/pika_slot_command.h Added Clone(net::MemoryPool* pool) to multiple slot command classes.
include/pika_stream.h Added Clone(net::MemoryPool* pool) to several stream command classes.
include/pika_transaction.h Added Clone(net::MemoryPool* pool) to transaction command classes and defined Execute() in ExecCmd.
include/pika_zset.h Added Clone(net::MemoryPool* pool) to multiple zset command classes.
src/acl.cc Updated CheckUserPermission and CheckCanExecCmd method signatures to use Cmd*.
src/pika_client_conn.cc Updated DoCmd and ReadCmdInCache methods to handle raw pointers.
src/pika_cmd_table_manager.cc Added GetRawCmd method and modified InitCmdTable for command size calculation.
src/pika_command.cc Updated DoBinlog to use this instead of shared_from_this().
src/pika_consensus.cc Updated ProposeLog, InternalAppendLog, and InternalAppendBinlog to accept Cmd*.
src/pika_dispatch_thread.cc Updated constructor to include memory_pool_page_size.
src/net/src/dispatch_thread.cc Updated constructor and NewDispatchThread function to include memory_pool_page_size.
src/net/src/worker_thread.cc Updated constructor to include memory_pool_page_size and integrated memory pool handling.
src/net/src/worker_thread.h Updated constructor signature and added MemoryPool memory_pool_;.
src/net/src/memory_pool.h Defined MemoryPool class for efficient memory management.

Sequence Diagram

sequenceDiagram
    participant Client
    participant PikaClientConn
    participant CmdTable
    participant MemoryPool
    participant Cmd

    Client->>PikaClientConn: Send Command
    PikaClientConn->>CmdTable: GetRawCmd()
    CmdTable-->>PikaClientConn: Return Cmd*
    PikaClientConn->>MemoryPool: Allocate Command
    MemoryPool-->>PikaClientConn: Allocated Cmd*
    PikaClientConn->>Cmd: Execute
    Cmd->>PikaClientConn: Return Result
    PikaClientConn->>MemoryPool: Deallocate Command

Poem

🐰 Hop, hop, through memory's maze,
Raw pointers dance in clever ways,
Pools of bytes, so swift and bright,
Pika's performance takes its flight!
Memory managed with rabbit's grace 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Dec 17 '24 12:12 coderabbitai[bot]

void func1() {
    MemoryPool pool;
    std::vector<C *> vector;
    vector.reserve(20);
    for (int i = 0; i < 1000000; ++i) {
        vector.clear();
        for (int j = 0; j < 20; ++j) {
            C *c = pool.Allocate<C>();
            vector.emplace_back(c);
        }
        for (const auto &item: vector) {
            pool.Deallocate(item);
        }
    }
}

void func2() {
    std::vector<C *> vector;
    vector.reserve(20);
    for (int i = 0; i < 1000000; ++i) {
        vector.clear();
        for (int j = 0; j < 20; ++j) {
            C *c = new C();
            vector.emplace_back(c);
        }
        for (const auto &item: vector) {
            delete item;
        }
    }
}

int main() {
    auto start = std::chrono::high_resolution_clock::now();
    func1();
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end - start;
    std::cout << "Function1 took  ms:" << elapsed.count() << " s:" << elapsed.count() / 1000.0f << std::endl;

    start = std::chrono::high_resolution_clock::now();
    func2();
    end = std::chrono::high_resolution_clock::now();
    elapsed = end - start;
    std::cout << "Function2 took  ms:" << elapsed.count() << " s:" << elapsed.count() / 1000.0f << std::endl;
    return 0;
}

image

用这个例子测试下来, 性能提升还是非常明显的

lqxhub avatar Dec 21 '24 09:12 lqxhub

只差功能验证和代码review

chejinge avatar Aug 29 '25 02:08 chejinge

Bot detected the issue body's language is not English, translate it automatically.


Only function verification and code review

Issues-translate-bot avatar Aug 29 '25 02:08 Issues-translate-bot