Efficiently create an array of values of a function

I have a function of four arguments, and I would like to have its values on the four-dimensional grid in an array. What is the most efficient way to produce this array, and how do I make it packed?

Let's say the function is

f[x1_,x2_,x3_,x4_] = Exp[ - (x1 - x2 + x3)^2 - (x2 + x3-x4)^2 ];


And I want to compute its values on the grid defined by (for all four variables)

dX = .25; xList = Range[ -5. , 5. , dX ];


So the best I could come up with was

A = Outer[ f , # , # , # , # ]& @ xList


This, unfortunately, takes quite a time to complete even for the grid having 41^4 elements while I would be happy to have a larger grid. Moreover, the produced array A is not packed. Is there a way to make the computation faster and pack the produced array?

• takes 12s on my laptop, if you do not loop over this that seems reasonable. In what context you you use this function? Commented Sep 6, 2017 at 13:41
• Maybe this can be used? Commented Sep 7, 2017 at 8:26
• Or maybe this is more relevant, as your function is listable and similar to the linked function. Commented Sep 7, 2017 at 8:30
• @Ruud3.1415 yep, it takes approximately the same time on mine, so 'takes quite a time' perhaps is not the best wording for my problem. The first issue here is that if I run, say, RandomReal to generate an array of the same size, it takes about 500 times less time. Second is a memory issue: the procedure scales with the size of the array to the extent that after a certain size the array does not fit into my RAM. That's why I asked about packing. Commented Sep 13, 2017 at 14:05
• @MariusLadegårdMeyer thanks a lot for the linked questions, compiling the function helped me to improve the performance. Commented Sep 13, 2017 at 14:06