You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浅拷贝与深拷贝在运行时及性能方面是否存在差异?

Shallow vs Deep Copy: Runtime & Performance Breakdown

Great question! It's easy to miss the differences when your test code seems to produce the same output, but under the hood, shallow and deep copies behave very differently—both in how they run and how they impact performance.

Runtime Behavior

Let’s break down what each copy actually does when your code executes:

  • Shallow copy (copy.copy()): This only duplicates the outermost container. All the nested elements inside are just references to the original objects. In your example, s = copy(l) creates a new list, but s[0] and l[0] point to the exact same sublist. That’s why modifying s[0][0] changes l too—you’re editing the shared nested object, not a copy of it.
  • Deep copy (copy.deepcopy()): This recursively duplicates every object in the entire nested structure. When you run d = deepcopy(l), you get a brand new list, and every sublist (and any deeper nested objects if you had them) are also brand new, completely disconnected from the original l. If you’d modified d[0][0] instead of s[0][0], l would stay unchanged—no shared references at all.

Performance Differences

The runtime behavior directly translates to clear performance gaps:

  • Speed: Shallow copies are significantly faster. They only do one level of copying, no recursion needed. Deep copies have to traverse every nested object, which adds up quickly—especially if you’re working with deeply nested structures (like a list of dictionaries containing lists, etc.).
  • Memory Usage: Shallow copies use far less memory because they reuse references to existing objects. Deep copies create duplicates of every single object in the hierarchy, so memory usage jumps up proportionally to the complexity of your data structure.

Quick Note on Your Test Code

In your snippet, you wrote p[0][0] = 1 which looks like a typo (probably meant d[0][0] = 1). If that’s the case, you might have made an error in execution—modifying the deep copy d should not change the original list l at all. Fix that typo and run the code again, and you’ll see the runtime difference immediately!

When to Use Which?

  • Reach for a shallow copy when: Your nested elements are immutable (like integers, strings, tuples) or you don’t plan to modify them. It’s fast and memory-efficient.
  • Use a deep copy when: You need a fully independent copy where changes to the replica won’t affect the original. This is non-negotiable if your nested structures are mutable and you need to edit them safely.

内容的提问来源于stack exchange,提问作者Hemel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:41:09