我有一个服务方法需要处理传入的对象:(顺便说一句,这是伪代码)
public class IncomingParentObject {
public Collection<IncomingChildOject> childObjects;
}
public Class IncmoingChildObject {
public String name;
}
我有一个“客户”的“注册表”,它关心传入子对象的一个子集。在注册时,我们只知道“名称”。客户端对象封装传输层转发信息的细节。
public class Registry {
// String represents the name in the child object
public Map<String, Set<Client>> clients;
}
现在服务类是这样的:
public void processIncmoingParentObject(IncomingParentObject parentObject) {
for (IncmoingChildObject childObject : parentObject.childObjects) {
Set<Client> clients = registry.clients.get(childObject.name);
for (Client client : clients) {
this.transportLayer.transportChildObject(childObject, client);
}
}
}
这会导致对 transportLayer 的多次调用(这可能很昂贵或很及时)。我想将其减少到基本上每个客户端一个 ChildObjects 子集的传输。
transportLayer.transport(Client client, Set<IncmoingChildObject> childObjects);
什么是有效的庄园扫描 parent 的 child 以确定要发送给客户的 child 的子集。
最佳答案
我会使用 map 来跟踪 Set<IncomingChildObject>
对于每个 Client
.
在未经测试的 Java 中:
public void processIncomingParentObject(IncomingParentObject parentObject) {
Map<Client,Set<IncomingChildObject>> childObjectsByClient =
new Map<Client,Set<IncomingChildObject>>();
for (IncomingChildObject childObject : parentObject.childObjects) {
Set<Client> clients = registry.clients.get(childObject.name);
for (Client client : clients) {
Set<IncomingChildObject> childObjects =
childObjectsByClient.get(client);
if (childObjects == null) {
childObjects = new Set<IncomingChildObject>();
childObjectsByClient.put(client, childObjects);
}
childObjects.add(childObject);
}
}
for (Entry<Client,Set<IncomingChildObject>> e : childObjectsByClient.entrySet()) {
this.transportLayer.transport(e.getKey(), e.getValue());
}
}
关于java - 我怎样才能改进这个实现以提高效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9099588/