[nnc] Eliminate redundant memory copy (#2984)
authorEfimov Alexander/AI Tools Lab/./Samsung Electronics <a.efimov@samsung.com>
Fri, 1 Feb 2019 09:52:37 +0000 (12:52 +0300)
committerGitHub Enterprise <noreply-CODE@samsung.com>
Fri, 1 Feb 2019 09:52:37 +0000 (12:52 +0300)
Do not copy memory in `Tensor::operator=` in case of constant argument

Signed-off-by: Efimov Alexander <a.efimov@samsung.com>
contrib/nnc/passes/soft_backend/code_snippets/cpp_header_types.def

index 09983ce..77efd9a 100644 (file)
@@ -145,14 +145,24 @@ public:
     std::memcpy(_data, data, num_elements * sizeof(float));
   }
 
-  Tensor &operator=(const Tensor &t)
-  {
-    assert(_managed);
-    if (this != &t)
-    {
-      reshape(t.getShape());
-      fillData(t._data, t._shape.getNumElems());
+  Tensor& operator=(const Tensor& t) {
+    if (this == &t)
+      return *this;
+
+    if (!t._managed) {
+      if (_managed)
+        delete _data;
+
+      _managed = false;
+      _data = t._data;
+      _shape = t._shape;
+    } else {
+      // this tensor is not constant so we can write data into it
+      assert(_managed);
+      reshape(t._shape);
+      fillData(t._data, _shape.getNumElems());
     }
+
     return *this;
   }