tags:

views:

81

answers:

3

Hi,

I have a system that returns a void* to a memory block. This memory block stores contiguous data records of different types(int,char,double etc.) and gives the number of bytes of each field in each record.I essentially look up the type of the record and get the value of the record. To retrieve all the records, I do

switch(type)

{

   case 'int' : \*(int*)(ptr+index)

   case 'char': \*(char*)(ptr+index)

}

When I have to go through 300000 records this is taking a lot of time.Is there a faster way to go through all the records?

A: 

If a single block can be of multiple types that can only be resolved at runtime, you will have to dispatch to handlers in a switch statement. Note that:

  1. unions are usually used in C for such things to save space
  2. switch statements are very fast and translate to constant-time lookup tables
Eli Bendersky
its actually continuous memory of various types..like int,char,int,double...so it would be 4 bytes,1 byte,4 bytes,8 bytes etc
Rajesh
@Eli, switch statements are not guaranteed to be constant-time lookup tables. It depends on whether compiler can optimize it or not.
Vlad Lazarenko
@Vlad: I assumed that for the simple case required by the author (dispatching with `switch` on an `enum` or small integer) today's compilers will optimize it
Eli Bendersky
@Rajesh: given a stream of binary data, how do you know the next 4 bytes are an int or a beginning of a double?
Eli Bendersky
I'm given the starting point of each record and its datatype/size
Rajesh
@Rajesh: then, as I said in the answer, apart from somewhat invalid C syntax your general direction is correct. `switch` on the type and get the record into the correct type of variable
Eli Bendersky
ok.tnx.I was hoping something better existed
Rajesh
@Rajesh: How are you fetching the `type` from the data? Maybe you have a Schlemiel painter problem?
pmg
A: 

If I understand your question correctly -- I assume you're going through each record, sortof saying "for each record i, if its type is 'char' then access the record at location i".

If you know how many records you have to access in advance, can't you just cache them all first?

If I'm completely off track forgive me for not understanding your point.

lorenzog
cache?..they are already in memory..I'm given a pointer to the first location
Rajesh
A: 

Your comments finally gave enough information to answer the question: you're writing to an ostringstream. Which means that you're probably doing a lot of string manipulation inside your switch. Figure out how to optimize this, and your performance problems should go away.

(to convince yourself this is the case, simply comment out all code that references the stream and run your program again)

Anon
The only operation I do is reading into a ostringstream which i use as a means of serialization to send over a socket. Are there better options for this?
Rajesh