0

I want to implement a Map of functions. I have several functions for inserting different data in SQLite database (InsertUSER_Data(), InsertMessages()) and so on. I want to create a Map and to call a specific function by a key command. As I see during search there are two approaches for this: anonymous classes and reflection. (e.g. here How to call a method stored in a HashMap? (Java)) I really like the approach based on Reflection API (via a Method type) : Map <String, Method> instead of just using anonymous classes which implement interface.

But I have doubts: is it a really big performance overhead in this solution, especially if I'll use it in Android or it's not really significant? Detail explanation will be very helpful.

Community
  • 1
  • 1
MainstreamDeveloper00
  • 8,436
  • 15
  • 56
  • 102
  • 1
    Why is it a map of reflective functions rather than a map of objects, each with a function? That's how the command pattern is normally handled in Java. What's different about yours? – Dave Newton Feb 25 '13 at 17:49
  • @DaveNewton I asked only about the performance penalty of using reflection for the realisation of Command Patter instead of just using Anonymous classes which implement interface – MainstreamDeveloper00 Feb 25 '13 at 17:53
  • Method.invoke in itself is not much heavier than calling the method on the object. Searching for the method, on the other hand, takes a lot of time. I suggest you try to cache the Method objects. – njzk2 Feb 25 '13 at 17:56
  • @njzk2 As I understood you proposed to create some data structure (e.g. ArrayList) which will store Method objects for every function I want to call, right? – MainstreamDeveloper00 Feb 25 '13 at 17:59

1 Answers1

3

I cannot answer your exact point, but some basics could help :

  • The art of knowing the performance beforehand is subtle, difficult and dangerous. The best way to do it is to measure the difference between the two solutions (that could be as simple as System.currentTimeMillis()).
  • As a rule of thumb, the time passed "in memory" will often be of little importance in terms of performance, in comparison with other things like IO (file or database acesses), remote calls or even something UI elements.
  • Except if you intend to do (b?)millions of calls, I sincerely doubt that such as small Map would be of consequence. But again, do not believe me, test it.

Finally, could your problem not be solve simply using interfaces ? That would remove this problem, and it is often easier to write, read, and debug. Something like :

interface Actionable { Result doStuff(Param p); }

That your various function classes could implement, and that would be possible to call afterwards without knowing exactly what is behind.

Martin
  • 7,634
  • 1
  • 20
  • 23