alcantula
alcantula

Reputation: 179

Python Deepcopy and Manual Copy Give Different Result

I am using deepcopy in my program. It works fine for the result. However, the usage of deepcopy make the performance of my program really slow. So, I try to do manual copy by creating the object itself. When I compare the performance, it gives better performance but the program result is different.

This is my code for deepcopy.

temp_location = deepcopy(self.locations)

And this is my code after replacing deepcopy with creating manual copy of the object.

temp_location = self.new_deepcopy(self.locations)

def new_deepcopy(self, locations):
    result = []
    for location in locations:
        result.append(Location(
           location.location_id,
           location.open_time,
           location.close_time,
           location.price,
           location.score,
           location.duration)
        )
    return result

self.locations is list of Location and Location is the object that I define like this.

class Location:
    def __init__(self, location_id, open_time, close_time, price, score, duration):
        self.location_id = location_id
        self.open_time = open_time
        self.close_time = close_time
        self.price = price
        self.score = score
        self.duration = duration
        self.waiting_time = 0
        self.visit_time = 0
        self.leave_time = 0

How to make the exact copy with different reference without using deepcopy? Why the new_copy that I create give the different result?

Upvotes: 0

Views: 98

Answers (1)

RomanHDev
RomanHDev

Reputation: 104

I think your 'new_deepcopy' is apparently not deep copying your variables. To my understanding of python (please correct me if i am mistaken) every variable in Python is a pointer to a memory location. So what your new_deepcopy is probably doing is just passing on this pointers to an object and not the actual values. And this is why your code seems to be faster but returns wrong results. If you want to improve the performance of your code you might want to consider the use of cython

Upvotes: 1

Related Questions