The current implementation of rmw_count_subscribers and rmw_count_publishers functions as a linear runtime complexity , O(N), w.r.t. the number of ROS2 topics published. This is not a big problem when the calling code has to count the number of ROS2 subscribers/publishers for a single topic, but it becomes a lot more of a performance problem when the calling code needs to count the number of ROS2 subscribers/publishers for each topic seen on ROS2. In that case, the runtime complexity becomes O(N^2) very easily.
It should be possible to re-write these methods to bring done the runtime complexity to either a constant or at least O(logN).
Here is a screenshot of the runtime analysis for rmw_count_publishers (counting the subscribers will have the same issues).
