Freitag, 29. Juli 2016

Java object-orientated vs. Java with a functional touch

Since Java 8 it looks like you can use parts from the functional paradigmen in the object-orientated language. These parts are based on functional interfaces. Also lambda-expressions are just another syntax to implement functional interfaces. But this advantages is not as functional as it seems, because functional interfaces are bases - in the end - on messages which are send to objects, which is object-orientated.
So the only thing functional interfaces does is enable another syntax to implement object-calls, which in fact is much more shorter and readeble in some cases.

When I think about parts from functional paradigm in object-orientated languages, better performance and avoiding of side-effects comes to my mind. But if you work wich object-calls in functional interfaces, you will never gain this advantages.

So if you use the functional touch of java you have to take care about the functional implementation. Then you will gain this advantages.

Here is an example that shows that a functional implementation with native types is more performant that an object-orientated implementation. (Both in Java):

Object-Orientated

   Set set = new HashSet<>();
  for (int i = 0; i < 1000000; i++) {
   set.add(new AdditionInteger(i));
  }

  Iterator it = set.iterator();
  AdditionInteger z1 = it.next();
  long start = System.currentTimeMillis();
  for (int i = 1; i < 1000000; i++) {
            z1.add( it.next());
  }
  long end = System.currentTimeMillis();

  System.out.println(end - start);
  // tooks 30261 ms

  // What about itration
  it = set.iterator();
  start = System.currentTimeMillis();
  for (int i = 1; i < 1000000; i++) {
   it.next();
  }
  end = System.currentTimeMillis();

  System.out.println(end - start);
  // tooks 47 ms



Functional 

              
  long start = System.currentTimeMillis();
  for (int i = 0; i < 1000000; i++) {
   i + (i + 1);
  }
  long end = System.currentTimeMillis();

  System.out.println(end - start);
  // tooks 8301 ms

So the functional code just took a third of the time the object-orientated code needed.
The reason might be the object-calls and the handling of the value inside the object, where the add-method was called. In functional languages you also have a space where values are stores, especially when they are bound to variables. This is space is calles environment. The handling of variables and values are not included in this experiment.