Is this the correct way of iterating through users and check if they have a determined permission?
That code works, but as you found out, it needs to load each user completely and is therefore very slow.

Unfortunately, the database schema of permissions/roles in D6 is really crappy. It stores all permissions of a role in a single role, separated with a comma.

But still, it should be possible to query that information directly. What you want to query is  which roles have a specific permission and then which users that have at least one of these roles.

Something like this:

db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {permission} p ON p.rid = ur.rid WHERE p.perm LIKE '%s'", '%, $permission_name_here,%');


There are a few special cases where this doesn't work/needs additional checks:


uid 1 does have all permissions
all users automatically have the authenticated user role (rid 2) but that is not stored in the users_roles table. So if a permission could possibly be assigned to that role, then you need to explicitly check that and if yes, return all users.
It is possible to dynamically assign roles to users based on some conditions. In this case, the query won't work for that...