使用 newInsance() 方法时内存泄漏

Memory leak when use newInsance() method

我有以下带有 for 循环的方法。我担心这样做会导致内存泄漏。 我的问题:对于 for 循环中的每个循环,newInstance() 方法是否真的会分配新的内存块?如果是这样,我是否应该在进入 for 循环之前创建一个 VehicleImpl 实例并尝试为此 VehicleImpl 实例设置新值。

private List<VehicleImpl> setVehicles(JsonInput input) {
    List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();

    Break lunch = Break.Builder.newInstance("Lunch")
            //timewindow(start time, end time), so lunch timewindow(start, start + duration)
            .setTimeWindow(TimeWindow.newInstance(input.getLunch().getStart(),
                    input.getLunch().getStart() + input.getLunch().getDuration()))
            //Lunch has highest priority
            .setPriority(1)
            //Lunch takes serviceTime
            .setServiceTime(input.getLunch().getDuration())
            .build();

    VehicleType type =  VehicleTypeImpl.Builder.newInstance("vehicleType")
            .setCostPerDistance(input.getCosts().getCostPerMeter())
            .setCostPerTransportTime(input.getCosts().getCostPerTransportSecond())
            .setCostPerServiceTime(input.getCosts().getCostPerServiceTime())
            .build();

    for(int i = 0; i < input.getNoVehicles(); i++) {
                                                //Name vehicle by index
        VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle " + String.valueOf(i+1))
                //The first location - depot location is indexed as 0 in Matrices
                .setStartLocation(Location.newInstance(i))
                .setBreak(lunch)
                .setLatestArrival(input.getOperating())
                .setType(type)
                .build();
        vehicles.add(vehicle);
    }
    return vehicles;
}

这里没有内存泄漏。只有一个临时引用变量在 for 循环的每次迭代中创建和销毁。您可以通过在 for 循环之前声明该变量来避免这种情况。