开发者社区 问答 正文

在C ++中使用数组或std :: vectors,性能差距是多少?

在我们的C ++课程中,他们建议不再在新项目上使用C ++数组。据我所知,Stroustroup本人建议不要使用数组。但是,性能存在明显差异吗?

展开
收起
保持可爱mmm 2020-01-16 16:44:13 457 分享 版权
1 条回答
写回答
取消 提交回答
  • new应避免将C ++数组与(即使用动态数组)一起使用。有一个问题,您必须跟踪大小,并且需要手动删除它们,并进行各种整理。

    不建议在堆栈上使用数组,因为您没有进行范围检查,并且将数组传递给周围将丢失任何有关其大小的信息(数组到指针转换)。boost::array在这种情况下,应使用将C ++数组包装在一个小类中,并提供一个size函数和迭代器对其进行迭代的情况。

    现在,将std :: vector与本机C ++数组(从互联网上获取):

    // Comparison of assembly code generated for basic indexing, dereferencing, // and increment operations on vectors and arrays/pointers.

    // Assembly code was generated by gcc 4.1.0 invoked with g++ -O3 -S on a // x86_64-suse-linux machine.

    #include

    struct S { int padding;

    std::vector v; int * p; std::vector ::iterator i; };

    int pointer_index (S & s) { return s.p[3]; } // movq 32(%rdi), %rax // movl 12(%rax), %eax // ret

    int vector_index (S & s) { return s.v[3]; } // movq 8(%rdi), %rax // movl 12(%rax), %eax // ret

    // Conclusion: Indexing a vector is the same damn thing as indexing a pointer.

    int pointer_deref (S & s) { return *s.p; } // movq 32(%rdi), %rax // movl (%rax), %eax // ret

    int iterator_deref (S & s) { return *s.i; } // movq 40(%rdi), %rax // movl (%rax), %eax // ret

    // Conclusion: Dereferencing a vector iterator is the same damn thing // as dereferencing a pointer.

    void pointer_increment (S & s) { ++s.p; } // addq $4, 32(%rdi) // ret

    void iterator_increment (S & s) { ++s.i; } // addq $4, 40(%rdi) // ret

    // Conclusion: Incrementing a vector iterator is the same damn thing as // incrementing a pointer. 注意:如果使用分配数组new并分配非类对象(例如plain int)或不使用用户定义的构造函数的类,并且您不想初始初始化元素,则使用new-allocated数组可能会带来性能优势,因为std::vector将所有元素初始化为构造上的默认值(例如,对于int来说是0) 问题来源于stack overflow

    2020-01-16 16:44:31
    赞同 展开评论