Fast intersection of sets: C++ vs C#

后端 未结 13 1660
野性不改
野性不改 2020-12-28 10:17

On my machine (Quad core, 8gb ram), running Vista x64 Business, with Visual Studio 2008 SP1, I am trying to intersect two sets of numbers very quickly.

I\'ve impleme

13条回答
  •  别那么骄傲
    2020-12-28 11:16

    One problem I see right away is that you're passing the sets in C++ by value and not by const reference. So you're copying them every time you pass them around!

    Also, I would not use a set for the target of set_intersection. I would use something like

    int runSetIntersection(const set& set1, const set& set2)
    {   
        vector intersection;
        intersection.reserve(10000) // or whatever the max is
    
        set_intersection(set1.begin(),set1.end(), set2.begin(), set2.end(), back_inserter(intersection));
    
        return intersection.size(); 
    }
    

    This code, however, still allocates inside the function. Even faster would be

    int runSetIntersection(const set& set1, const set& set2, vector& scratch)
    {   
        scratch.reserve(10000) // or whatever the max is
    
        set_intersection(set1.begin(),set1.end(), set2.begin(), set2.end(), back_inserter(scratch));
    
        return scratch.size(); 
    }
    

    And then allocate scratch before you start the timer.

    Though, if you're just looking for the size, a hand-written for loop, combined with set::find might give even better results.

提交回复
热议问题