java - 我怎样才能改进这个实现以提高效率

标签 java algorithm

我有一个服务方法需要处理传入的对象:(顺便说一句,这是伪代码)

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/

相关文章:

c# - 如果我知道背景颜色,如何创建图像轮廓?

algorithm - 在 Delphi 中快速填充字符串

java - 字节码和目标代码有什么区别?

java - 如何保存和显示应用程序制作的照片

java - "could not initialize a collection"+ @Lob + MSSQL

algorithm - 快速排列 -> 数字 -> 排列映射算法

algorithm - 一般位计数

java - 解析带有闰秒的持续时间,如 00 :00:60

java - 为什么我的程序无法识别输入 "q"并中断循环?

Java 递归参数值