# Follow-up to “How to differentiate formally?”: Efficiency concern

In link to "how to differentiate formally?" and particularly to the answer by @Jens, I want to do something like this:

Clear[sum,x,A,n1,n2,result];
sum = Sum[x[i,j] A[j], {i,1,n1},{j,1,n2}];
result = D[sum,x[a,b], NonConstants -> {x}];
x /: D[x[i_,j_], x[k_,l_], NonConstants -> {x}] :=
KroneckerDelta[i,k]*KroneckerDelta[j,l];
Timing[result]

(that is to say differentiate with NonConstants and then evaluate while applying the KroneckerDelta rule, which is what takes times).

This takes a long time (~6sec in this minimal example, a prohibitive time in the case of my actual application), but when re-executing the cell (or another cell with copy-pasted content), it is much faster (~0sec in this example).

I believe this is because during the first run Mathematica tries out different un-optimized ways to do what it is asked to do, and at second run it uses the optimal way for the given types and variables.

My question is: how can I input informations ressembling those Mathematica found out during the first run to directly do the fast calculation ?

EDIT: An element of an answer can come from "Simplification of double symbolic sums containing a DiscreteDelta without explicit summation range", adapted to :

Clear[sum,x,A,n1,n2,result];
sum = Sum[x[i,j] A[j], {i,n1}, {j,n2}] ;
result = D[sum, x[a, b], NonConstants -> {x}];
x /: D[x[i_,j_], x[k_,l_], NonConstants -> {x}] := HIS[i,k,j,l];
Timing[result]

which is very fast. (Note the summation is in the form {i,n1}, and, in the link above, the HoldForm/ReleaseHold succession to evaluate the HIS function.)

This does not answer the question, but offers a nice workaround.