0

I have the following code:

(let [obs ^java.util.Observer (proxy [java.util.Observer] []
              (update [^Object o ^String arg]
                (println arg)))
        network ^StockPriceNeuralNetwork (NeuralNetworkFactory/createStockMarketNeuralNetwork ^java.util.List [^java.util.Observer obs])]
    (.trainForTime ^StockPriceNeuralNetwork network))

The problem is from Java this code runs about 100x faster than it does calling it from Clojure once the code has been compiled. Is there any way I can get the same Java performance calling it from Clojure or will it always be slower?

1 Answer 1

8

There are way more typehints than necessary here, and the ones you do have are placed such that I'm not entirely sure they are doing any good - you really are supposed to hint the name in a let, not the value. That is, (let [^Observer obs (...)] ...), not (let [obs ^Observer (...)] ...). In many cases both of these will work, but the former is much "safer". It's also true that you should strongly prefer reify over proxy here, both for performance and because proxy is discouraged when you can possibly avoid it.

I don't know what neural network library you're using, so you may need a single typehint on the argument to createStockMarketNeuralNetwork, but the rest are serving no purpose except to confuse anyone who reads your code - it's even possible that excessive typehints will confuse the compiler into writing slower code, if you choose hints that aren't accurate. So instead of placing them at random throughout your code, switch to the reify approach sw1nn suggests, and then set *warn-on-reflection* to true and see what, if any, reflection is an issue. Below is a version of this code with reify, and after removing all the typehints that I know make no difference:

(let [obs (reify java.util.Observer
            (update [this o arg]
              (println arg)))
      ^StockPriceNeuralNetwork network (NeuralNetworkFactory/createStockMarketNeuralNetwork ^java.util.List [obs])]
  (.trainForTime network))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.