Skip to content

getBytes 内部建议用 memcpy_s 实现 #3

Closed

Description

@abevol

性能大概有几百倍的差距

    void getBytes(uint8_t* buf, uint32_t  len)
    {
        if (0 == memcpy_s(buf, len, p_buffer_ + position_, remaining()))
            position_ = position_ + len;
    }
    void getBytes(uint32_t index, uint8_t* buf, uint32_t len) const
    {
        memcpy_s(buf, len, p_buffer_ + index, limit_ - index);
    }

Activity

  1. CPythoner commented on Apr 3, 2026

    @CPythoner
    Owner

    @abevol 您好!

    感谢您的建议。我已经创建了 PR #7 来修复这个问题。

    修改内容

    将 getBytes 方法的实现从循环拷贝改为使用 memcpy:

    修改前:

    void getBytes(uint8_t* buf, uint32_t len)
    {
        // 合法性检测
        if (!p_buffer_ || position_ + len > limit_)
            return;
    
        for (uint32_t i = 0; i < len; i++)
        {
            buf[i] = p_buffer_[position_++];
        }
    }

    修改后:

    void getBytes(uint8_t* buf, uint32_t len)
    {
        if (!p_buffer_ || position_ + len > limit_)
            return;
    
        memcpy(buf, p_buffer_ + position_, len);
        position_ += len;
    }

    性能提升

    正如您所说,使用 memcpy 替代循环拷贝可以带来显著的性能提升(几百倍的差距)。memcpy 是底层优化的内存拷贝函数,可以避免循环开销并可能利用 SIMD 指令进行批量拷贝。

    PR 链接:#7

    期待您的 review!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions