Array mutation optimization in Clojure

After reading a few blog posts on this subject, I found that I mutated an array in Clojure as follows:

(defn m [xs ys] (dotimes [i (count xs)] (aset #^ints ys (int i) (int (* (int 3) (int (aget #^ints xs (int i)))))))) 

where (def xs (into-array Integer/TYPE (range 1000000))) and (def ys (into-array Integer/TYPE (range 1000000)))

took an average of 14 ms according to the criterion, whereas Java do the same,

 public static int[] m(int[] x, int[] y) { for(int i=0; i<x.length; i++) y[i] = 3*x[i]; return y; } 

takes an average of 800us. **

I am doing everything in my power to speed up the work and are there any other ways to optimize?

** I timed their use of Criterium with (report-result (bench (m xs ys )) :verbose) and (report-result (bench (. Test m xs ys)) :verbose)

+6
source share
2 answers

Try this on Clojure 1.3:

 (set! *unchecked-math* true) (defn m [^longs xs ^longs ys] (dotimes [i (count xs)] (aset ys i (* 3 (aget xs i))))) 
+5
source

If you need speed, you need to enter the world of primitives and not leave it until you finish. This is useless, starting with the boxed Integer i , and then converting it to a primitive on each usage site. Perhaps you can make dotimes produce ints (type hint declaration i ), but not sure. What I know is a loop-recur with primitive loop vector initializers: (loop [i (int 0)] ... (recur (unchecked-inc i)) . Also, in your example, you have (int 3) .You need to let in advance so as not to repeat the decompression at each iteration.

By the way, you can use (int-array (range 1000000)) to create your initialized array and just (int-array 1000000) for empty.

UPDATE

As with Clojure 1.3, with improved support for primitives, most of what I wrote above no longer applies. dotimes already uses primitive arithmetic, so all you need to write to get full performance is

 (dotimes [i (alength ^ints xs)] (aset ^ints ys i (unchecked-multiply (aget ^ints xs i) 3) 

Basically, no int constructors are needed and use unchecked-multiply .

+5
source

Source: https://habr.com/ru/post/913298/


All Articles