Say I have the following code
(let [a (some-function 3) b (some-function (+ 1 2)) ca] (= ab))
Suppose some-function returns a very big data structure (say one million sized array)
First question: how much memory will clojure allocate? Will it allocate memory for each of these 3 vectors or they will share the same data structure?
Second question (closely related): how fast would it be to compare them? Will =
iterate over each element or not?
This simplified example may look dumb but there are similar real life situations where this matters a lot like
(map some-function [1 23 1 32 1 44 1 5 1 1 1 1])
EDIT
in my specific case, some-function
returns a conj
of two sets which may be very big
Whether a
and b
share the structure depends entirely on what some-function
does. It's impossible to answer without any details. c
and a
will be bound to the same value, so no additional memory allocation for c
.
In general, semantics and behavior of =
depend on what values you compare. If you compare collections, then yes, =
will iterate through each element until it either exhausts them, or finds the first pair of unequal ones.
Additionally:
=
will first check if the objects being compared are the same (reference equality,) so comparison of a
and c
will be instant.
While it's impossible to say for certain if different some-function
invocation return the same or different structure, chances are without memoization they will be different. Just wrap your some-function
using memoize
to be certain there is no double allocation (of course assuming your some-function
is pure.) As simple as
(def some-function (memoize some-function))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.