Hello all,
I just discovered this place about a week ago and it seems like a great bunch of people.
I would like to submit a short program and see what you folks think about optimization of
java code. The following is a short randomizing algorithm that I wrote which can be used to create passwords and such. The result is a character sequence of upper and lower case characters and numbers the length that you type into the shell. (ex. java CraigsRandomizer 50 -- would produce a sequence of 50 characters) It will tell you how many characters you chose, the processing time in milliseconds, and display the result. Just copy, paste, compile, and your off.
Here is the code:
You will probably note that you have to make the length more then 100-200 to start getting any processing time indication at all. The processing time result is relative to the amount of characters that are generated which quickly meet the specification.
The program uses Math.random() and creates an array of "len" characters which meet the specification.
Steps I took to optimize the code:
1) The class and method are final to maximize compilation.
2) Short circuit comparison operators are used and the comparisons listed from the largest group to the smallest group for fastest rejection.
3) An array of primitives is used and discarded for quick access and memory size.
4) Math.random() * 122 limits the result to numbers which do not exceed our needs.
Please disregard the three lines of code which are for displaying the timing and print the messages to the screen. They are just for the purpose of this discussion.
Also I am aware of the opinion that the java.lang.Math.random() does display certain consistencies and that other algorithms can produce more random results. For this purpose it is certainly random enough.
Are there any further ways to optimize this?
What about the two casts?
Would a different algorithm be faster?
Is there a more efficient way to handle memory?
Thanks for your time,
Best Regards,
Craig
(fixed formating)
[This message has been edited by Craig O'Brien (edited March 01, 2001).]