Skip to content

Caching method calls

earlzero edited this page Nov 23, 2016 · 9 revisions

Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react

All new develpoment on cyclops occurs in cyclops-react. Older modules are still available in maven central.

screen shot 2016-02-22 at 8 44 42 pm

Memoizing method calls

Cyclops Memoize class makes it simple to cache the result of method calls.

See also Memoisation,-Currying,-Uncurrying-and-Type-Inferencing

Example memoize a method reference

        int called = 0; // instance variable
	
	QuadFunction<Integer,Integer,Integer,Integer> cached = Memoize.memoizeQuadFunction(this::addAll);
		
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(called,equalTo(1));
	
	
	private int addAll(int a,int b,int c, int d){
		called++;
		return a+b+c+d;
	}

Cleaner type inference with Lombok val (entirely optional)

        int called = 0; // instance variable
	
	val cached = memoizeQuadFunction(this::addAll);
		
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(cached.apply(1,2,3,4),equalTo(10));
	assertThat(called,equalTo(1));
	
	
	private int addAll(int a,int b,int c, int d){
		called++;
		return a+b+c+d;
	}
Clone this wiki locally