I'm trying to return an integer from a non-linear set of integers in a given case. The values in each cases array remain constant. This function can be called numerous times throughout running. Any suggestions to an efficient and error free approach would be greatly appreciated.
My code looks something similar to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
uint32 Class::ExampleFunction(uint32 arg) {
switch (arg) {
case 1:
uint32 IntArray[] = { 1, 8, 32, 64, 128 };
return IntArray[RandIntIndex]; // Let's pretend RandIntIndex exists and returns a random value in the index.
// Also, this would be an error as it ceases to exist?
case 2:
uint32 IntArray[] = { 99, 44, 53 };
return IntArray[RandIntIndex];
default:
return 0;
}
}
A multidimensional array sounds like it'd work perfectly. Out of curiosity though, let's say one array contains twenty-five elements while the majority of them contain five. Now let's say I have thirty indices. How inefficient would that be considering the majority of indices only store five integers? It's probably fairly negligent in my example but you understand my direction. Also, what's the difference between creating a multidimensional array or creating multiple static arrays? (In terms of how bad it'd be run time wise)
Sorry for the newbie questions :) hope it made more sense this time.
Edit: Also, would a database be a good direction? I'm assuming a SQL query would be less intense than large arrays.
These are all good questions. Let's start with the most important one:
Also, would a database be a good direction?
The access time for a fast disk these days is what? 5milliseconds? In contrast, a 2GHz processor can execute an instruction in about 0.5 nanoseconds. So burn this into your brain: disk is a MILLION times slower than RAM. So a database is probably a really bad idea, especially for such a small amount of data.
Out of curiosity though, let's say one array contains twenty-five elements while the majority of them contain five. Now let's say I have thirty indices.
If you're running on a 64 bit machine then 25 elements times 30 indices times 8 bytes each is 6,000 bytes. Not a whole lot on a PC but on a smaller device it might matter. So maybe check for the 25-element index and if it isn't that one then use the array.
Also, what's the difference between creating a multidimensional array or creating multiple static arrays?
No real difference in size but how would you access multiple static arrays? Maybe a switch statement? That might be slower than a multidimensional array access.
These are all interesting things that are worth knowing, but it's also true that premature optimization is the root of most evil. Will the size and speed of this code affect you application? If not, then you may be fretting needlessly.