1

The standard line on OOP features in Fortran is that they are good for readability and re-use, but bad for execution time. I'm getting mixed results when I test it.

I wrote a simple dummy program to test this by adding two large arrays inside a derived type.

type oop
  real(8),allocatable,dimension(:,:,:) :: array
contains
  procedure :: plusOOP,eqPlus
  generic   :: operator(+) => plusOOP
end type
type(oop) function plusOOP(a,b) result(c)
  class(oop),intent(in) :: a,b
  c%array = a%array+b%array
end function plusOOP
subroutine eqPlus(c,a,b)
  class(oop),intent(in)    :: a,b
  class(oop),intent(inout) :: c
  c%array = a%array+b%array
end subroutine eqPlus

I found that call c%eqPlus(a,b) is just as fast as adding standard arrays. However, this is seems less clear than just writing c%array = a%array+b%array. Unfortunately, c=a+b is around two times slower for arrays with more than 1M values. (For arrays with less than 500K values c=a+b was just as fast but this probably depends on the specific computer.)

Is the real problem with the OOP style the tendency to write everything as functions instead of subroutines? Is there a way to get c=a+b that doesn't have this overhead for large arrays?

weymouth
  • 521
  • 6
  • 17
  • It will be processor dependent a lot. Did you try also to call the function directly? These days compiler writers concentrate on how to implement these things to work reliably, not on speed. In theory it should be able to optimize both to the same machine code, but it is not what we have now. – Vladimir F Героям слава Apr 29 '13 at 16:56
  • Yeah, I tried that and an unhealthy number of other permutations - same factor slower. I am not going to complain about reliability, though. – weymouth Apr 30 '13 at 06:53

1 Answers1

1

If you think about it, using functions will be a lot slower since

  1. Memory has to be allocated for the return value
  2. When the function returns, the data has to be copied to the receiving variable
  3. The temporary memory has to be discarded.

When calling a subroutine, all you need to do is write the result directly to the output variable.

OOP style isn't about writing everything in functions: that is just for convenience so that someone reading the code can understand it more easily. OOP is more about objects owning data and being responsible for managing their own data.

cup
  • 7,589
  • 4
  • 19
  • 42