diff --git a/backends/verilog/verilog_backend.cc b/backends/verilog/verilog_backend.cc
index 04b87b40d..6a81a31c9 100644
--- a/backends/verilog/verilog_backend.cc
+++ b/backends/verilog/verilog_backend.cc
@@ -2334,17 +2334,23 @@ void dump_module(std::ostream &f, std::string indent, RTLIL::Module *module)
 	f << stringf("%s" "module %s(", indent.c_str(), id(module->name, false).c_str());
 	bool keep_running = true;
 	int cnt = 0;
-	for (int port_id = 1; keep_running; port_id++) {
-		keep_running = false;
-		for (auto wire : module->wires()) {
-			if (wire->port_id == port_id) {
-				if (port_id != 1)
-					f << stringf(", ");
-				f << stringf("%s", id(wire->name).c_str());
-				keep_running = true;
-				if (cnt==20) { f << stringf("\n"); cnt = 0; } else cnt++;
-				continue;
-			}
+	int max_port_id = 0;
+	for (auto wire : module->wires()) {
+		max_port_id = std::max(wire->port_id, max_port_id);
+	}
+	std::vector<Wire *> wires(max_port_id + 1, nullptr);
+	for (auto wire : module->wires()) {
+		wires[wire->port_id] = wire;
+	}
+	for (int port_id = 1; port_id <= max_port_id; port_id++) {
+		Wire *wire = wires[port_id];
+		if (wire) {
+			if (port_id != 1)
+				f << stringf(", ");
+			f << stringf("%s", id(wire->name).c_str());
+			keep_running = true;
+			if (cnt==20) { f << stringf("\n"); cnt = 0; } else cnt++;
+			continue;
 		}
 	}
 	f << stringf(");\n");