4
$\begingroup$

When

a = 1;

is executed, an ownvalue will be stored in symbol a, and the rule corresponding to ownvalue defined for a can be given by

OwnValues@a
(* {HoldPattern[a] :> 1} *)

My question is, is ownvalue unique in Mathematica? Can we achieve the same result and (at least almost) the same performance as ownvalue, with other functions?

Replace / ReplaceAll / With can give us the same result, but they're much slower:

a = 1;
Do[a, {10^6}] // AbsoluteTiming
Clear@a
(* {0.031268, Null} *)

Do[a /. {HoldPattern[a] :> 1}, {10^6}] // AbsoluteTiming
(* {1.456692, Null} *)

Do[Replace[a, {HoldPattern[a] :> 1}], {10^6}] // AbsoluteTiming
(* {1.518485, Null} *)


Do[With[{a = 1}, a], {10^6}] // AbsoluteTiming
(* {0.401429, Null} *)
$\endgroup$
3
$\begingroup$

Association is as close to what you seem to want as I am aware of:

asc = <|"a" -> 1|>;

Do[asc["a"], {10^6}] // RepeatedTiming

(* {0.2063, Null} *)

Eliminating the look-up of asc itself makes this somewhat faster:

With[{asc = <|"a" -> 1|>},
  Do[asc["a"], {1*^6}] // RepeatedTiming
]

(* {0.142, Null} *)

Incidentally I think the "ownvalues" evaluation may not be as fast as it appears. I mean that I think there may be optimization taking place that hides the actual look-up cost.


I am unable to support my conjecture above regarding optimizations. Building a complete expression and then evaluating it is still much faster for Symbol lookup:

a = 1;
foo = Join @@ ConstantArray[Hold[a], 1*^6];
List @@ foo // RepeatedTiming // First

(* 0.0380 *)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.