NeuralGenetic icon indicating copy to clipboard operation
NeuralGenetic copied to clipboard

Use numpy.asarray instead of numpy.array to avoid unnecessary copying

Open SaFE-APIOpt opened this issue 7 months ago • 1 comments

https://github.com/ahmedfgad/NeuralGenetic/blob/54be7a6a860593eb3853d6a3deb207eaf35eea9f/Tutorial Project/ga.py#L13 In the line: return numpy.array(pop_weights_vector) a better alternative would be: return numpy.asarray(pop_weights_vector) numpy.array() always attempts to create a new array, even if the input is already a NumPy array. This introduces unnecessary memory copying and additional overhead. On the other hand, numpy.asarray() checks whether the input is already an array and avoids copying if it's not needed, resulting in better performance and memory efficiency.

If the goal is simply to ensure that pop_weights_vector is returned as an array, np.asarray() is the more optimal and lightweight choice. This change preserves the same functionality while improving execution efficiency, especially in performance-critical sections or when handling large data structures.

SaFE-APIOpt avatar Mar 17 '25 15:03 SaFE-APIOpt