CFD Online Discussion Forums

CFD Online Discussion Forums (
-   OpenFOAM Programming & Development (
-   -   Difference: A.internalField()[celli] and A[celli] ? (

kalle November 29, 2012 04:44

Difference: A.internalField()[celli] and A[celli] ?

When accessing cell values in a volScalarField, it seems that both A.internalField()[celli] and A[celli] does what I want. I can both read values and set values. I've seen that both practices are found in the source code. The thermo libraries usually creates scalarField references to internalField, and then use them, hence they use the first method (A.internalField()[celli]), while other classes use A[celli].

Does anyone know what the difference is? Is there any, and are there any performance related differences?


hjasak November 30, 2012 09:56

The difference is only some safety. The access is the same because of derivation, but there is a side-effect.

Whey you do runTime++, the field needs to decide when to safe the old-time level (if required). For this purpose, the non-const access to internalField() and boundaryField() will check if the old-time level has been updated; if not, a copy of CURRENT FIELD is stored as the old-time level before granting access.

This means:
- if you use the derivation access A[cellI], you will circumvent this mechanism and may screw up your old-time level handling (it would use the reset value)
- if you are accessing internal field of A, it is really bad to do:

forAll (cells, cellI)
A.internalField()[celli] = 55;

because this puts an if in the loop (old-time checking), which kills your performance.

Instead you should do:

scalarField& AIn = A.internalField();

forAll (AIn, cellI)
AIn[cellI] = 55;

and you are MUCH faster.



(P.S. Good question; I wonder how many people actually know this)

kalle December 3, 2012 02:24

Dear Hrv,

thanks a lot for your answer. I did not realized there was a significant difference if you used a scalarField&, instead of directly addressing the internalField() in the loop. This will clearly have impact on my coding habits. (and likely on my code's performance :-)


All times are GMT -4. The time now is 01:03.