Why is valarray so slow?

后端 未结 7 2017
情书的邮戳
情书的邮戳 2020-12-23 15:18

I am trying to use valarray since it is much like MATLAB while operating vector and matrices. I first did some performance check and found that valarray cannot achieve the p

7条回答
  •  没有蜡笔的小新
    2020-12-23 15:30

    I suspect that the reason c = a*b is so much slower than performing the operations an element at a time is that the

    template valarray operator*
        (const valarray&, const valarray&);
    

    operator must allocate memory to put the result into, then returns that by value.

    Even if a "swaptimization" is used to perform the copy, that function still has the overhead of

    • allocating the new block for the resulting valarray
    • initializing the new valarray (it's possible that this might be optimized away)
    • putting the results into the new valarray
    • paging in the memory for the new valarray as it is initialized or set with result values
    • deallocating the old valarray that gets replaced by the result

提交回复
热议问题