From the above example: variable xyz is assigned to value 5, here Variables abc and axz prints the five random Numbers. we can see the Output values of abc & axz in the environment Pane.
Variable abc contains :
-0.876124530, 0.190421711 , 0.006127489, 1.852267401, 0.530870030
Variable axz contains :
-1.3806327, -0.7074115 , -1.3106574 , 2.0746617 , -0.1044966
Lets do this example in vectorized approach & De-Vectorized approach :
Source pane :
vectorized approach :
From the above code, we are doing vectorized approach in Line 8 and Line 9.
In this approach, we are straight forwardly doing the summation of two Vectors abc & axz and result is stored in ayc Variable
ayc : -0.3721198 , -1.6758642, -1.1012545 , 2.5531083 , -3.3600397
Now Let’s Do De-vectorized approach :
From the above code, we are doing De- vectorized approach from Line 13 to Line 18.
In this approach, First replicate an empty vector using rep Function, This will replicate 5 Empty spaces (Memory). using for loop iterations the summation is performed from index of first vector to index of next vector .
Please refer the below image to get more clarity
However the results for Vectorized & De-vectorized approaches are identical , But there are few differences in terms of performance & Code Readability.
- The Vectorized Code is more concise, easy to read, and less error prone.
- The memory allocated will be less and execution Time is also less compared to De-Vectorized Code
Now let’s check the memory allocated & Execution Time for Vectorized & De-vectorized Code:
Vectorized Code :
Here The Variable xyz = 1000, and abc Variable Prints 1000 Random Numbers, axz variable prints 1000 Random Numbers, select all the Lines from 1 to 10 Run the code and To check the Memory size and execution Time, click on Profile from menu and choose Profile selected Lines.
Here from the below screen shot, we can see The Memory allocated is 0 MB and execution Time is 10 Micro seconds.
De-Vectorized Code :
Here The Variable xyz = 1000, and abc Variable Prints 1000 Random Numbers, axz variable prints 1000 Random Numbers, select all the Lines from 1 to 15 Lines ,Run the code and click on Profile from menu and choose Profile selected Lines.
Here from the below screen shot, we can see The Memory allocated is 0.2 MB and execution Time is 20110 Micro seconds, which is around 21 Seconds .