What is the fastest portable way to copy an array in C++

后端 未结 8 517
面向向阳花
面向向阳花 2020-12-30 02:11

This question has been bothering me for some time. The possibilities I am considering are

  1. memcpy
  2. std::copy
  3. cblas_dcopy

Does a

8条回答
  •  礼貌的吻别
    2020-12-30 02:52

    In C++ you should use std::copy by default unless you have good reasons to do otherwise. The reason is that C++ classes define their own copy semantics via the copy constructor and copy assignment operator, and of the operations listed, only std::copy respects those conventions.

    memcpy() uses raw, byte-wise copy of data (though likely heavily optimized for cache line size, etc.), and ignores C++ copy semantics (it's a C function, after all...).

    cblas_dcopy() is a specialized function for use in linear algebra routines using double precision floating point values. It likely excels at that, but shouldn't be considered general purpose.

    If your data is "simple" POD type struct data or raw fundamental type data, memcpy will likely be as fast as you can get. Just as likely, std::copy will be optimized to use memcpy in these situations, so you'll never know the difference.

    In short, use std::copy().

提交回复
热议问题