Perform a collection of commands as fast as possible in Java

120 views Asked by At

in my project I want to load a large amount of functions from a script into a collection to hold them and perform them later (probably many times) without reading the script again. I need the Access to the functions to be as fast as possible and thought about two ways of doing so:

  1. Command Pattern: My first idea was to store the script commands as objects (command pattern) inside of a collection and perform all of them within a for-each-loop when I need to perform the script. Although the Code will be easier to read I think it will cost a lot of performance and memory to access all the different commands through objects.

    for (Command command : commandList) { command.execute();

  2. Collection of chars and Switch Case: My second Idea was to store primitive variables like char or int into a collection and put a switch-case construct inside a for-each-loop. I would use primitives because I think its faster then i.e. String objects. Therefore I would use a library like Trove. I think this way it could be faster than the command pattern because no command object has to be accessed. Moreover, less memory will be occupied. On the other hand i think it could be slower because the command pattern can access the right function directly while the switch-case construct has to check many times if the char is a,b,c,d and so on.

    for (char command : commandList) { switch(command){ case 'a': doA(); break; case 'b': doB(); break; case 'c': ... } }

Do you think one way is better? Do you know another way? Which type of collection would you recommend?

2

There are 2 answers

0
bigGuy On

I think second aproach is better.

On the other hand i think it could be slower because the command pattern can access the right function directly while the switch-case construct has to check many times if the char is a,b,c,d and so on.

Compiler will take care and optimize it. If your script file size is not in GB, it doesn't matter.

0
Stratege On

Your question boils down to: Polymorphism vs Switch statement.

The former is better maintainable and readable since there is no need to slug through a large switch statement using magic numbers as its keys (or chars in your case) whenever one wants to know what is happening or add to it.

In terms of performance either should be rather negligible and highly optimized since they are very common and simple cases, thus it is better to worry about readability/maintainability than optimisation and therefor Polymorphism is better.