Quickly find whether a value is present in a C array?

前端 未结 15 1307
灰色年华
灰色年华 2021-01-29 17:30

I have an embedded application with a time-critical ISR that needs to iterate through an array of size 256 (preferably 1024, but 256 is the minimum) and check if a value matches

15条回答
  •  佛祖请我去吃肉
    2021-01-29 17:50

    If you can accommodate the domain of your values with the amount of memory that's available to your application, then, the fastest solution would be to represent your array as an array of bits:

    bool theArray[MAX_VALUE]; // of which 1024 values are true, the rest false
    uint32_t compareVal = 0x1234ABCD;
    bool validFlag = theArray[compareVal];
    

    EDIT

    I'm astounded by the number of critics. The title of this thread is "How do I quickly find whether a value is present in a C array?" for which I will stand by my answer because it answers precisely that. I could argue that this has the most speed efficient hash function (since address === value). I've read the comments and I'm aware of the obvious caveats. Undoubtedly those caveats limit the range of problems this can be used to solve, but, for those problems that it does solve, it solves very efficiently.

    Rather than reject this answer outright, consider it as the optimal starting point for which you can evolve by using hash functions to achieve a better balance between speed and performance.

提交回复
热议问题