Skip to content

Commit 7135be1

Browse files
committed
PollSelector: optimize fd index lookup
1 parent e583c0d commit 7135be1

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

src/server/select.d

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,8 @@ final class PollSelector : Selector
288288
import core.sys.posix.poll;
289289
}
290290

291-
private pollfd[] pollfds;
291+
private pollfd[] pollfds;
292+
private size_t[socket_t] fd_idxs;
292293

293294
this(Duration timeout)
294295
{
@@ -303,11 +304,14 @@ final class PollSelector : Selector
303304

304305
const pfd = create_pollfd(fd, events);
305306

306-
if (is_registered)
307-
pollfds[find_fd_idx(fd)] = pfd;
308-
else
307+
if (is_registered) {
308+
const idx = fd_idxs[fd];
309+
pollfds[idx] = pfd;
310+
}
311+
else {
312+
fd_idxs[fd] = pollfds.length;
309313
pollfds ~= pfd;
310-
314+
}
311315
fd_events[fd] |= events;
312316
}
313317

@@ -318,11 +322,16 @@ final class PollSelector : Selector
318322

319323
fd_events[fd] &= ~events;
320324
const remaining_events = fd_events[fd];
321-
size_t idx = find_fd_idx(fd);
325+
const idx = fd_idxs[fd];
322326

323327
if (remaining_events == 0) {
324328
fd_events.remove(fd);
329+
fd_idxs.remove(fd);
330+
325331
pollfds[idx] = pollfds[$ - 1];
332+
const swapped_fd = cast(socket_t) pollfds[idx].fd;
333+
if (swapped_fd != fd) fd_idxs[swapped_fd] = idx;
334+
326335
pollfds.length--;
327336
return;
328337
}
@@ -367,14 +376,6 @@ final class PollSelector : Selector
367376
return pfd;
368377
}
369378

370-
private size_t find_fd_idx(socket_t fd)
371-
{
372-
foreach (i, ref pfd; pollfds)
373-
if (pfd.fd == fd)
374-
return i;
375-
return size_t.max;
376-
}
377-
378379
@trusted
379380
private int wait()
380381
{

0 commit comments

Comments
 (0)