简体   繁体   中英

Why is this C-style code 10X slower than this obj-C style code?

//obj C version, with some - less than one second on 18,000 iterations

for (NSString* coordStr in splitPoints) {

  char *buf = [coordStr UTF8String];
  sscanf(buf, "%f,%f,", &routePoints[i].latitude, &routePoints[i].longitude);

  i++;

}

//C version - over 13 seconds on 18,000 iterations

for (i = 0; buf != NULL; buf = strchr(buf,'['), ++i) {

  buf += sizeof(char);
  sscanf(buf, "%f,%f,", &routePoints[i].latitude, &routePoints[i].longitude);

}

As a corollary question, is there any way to make this loop faster?

Also see this question: Another Speed Boost Possible?

Measure, measure, measure.

Measure the code with the Sampler instrument in Instruments.

With that said, there is an obvious inefficiency in the C code compared to the Objective-C code.

Namely, fast enumeration -- the for(x in y) syntax -- is really fast and, more importantly, implies that splitPoints is an array or set that contains a bunch of data that has already been parsed into individual objects.

The strchr() call in the second loop implies that you are parsing stuff on the fly. In and of itself, strchr() is a looping operation and will consume time, more-so as the # of characters between occurrences of the target character increase.

That is all conjecture, though. As with all optimizations, speculation is useless and gathering concrete data using the [rather awesome] set of tools provided is the only way to know for sure.

Once you have measured, then you can make it faster.

Having nothing to do with performance, your C code has an error in it. buf += sizeof(char) should simply be buf++ . Pointer arithmetic always moves in units the size of the type. It worked fine in this case because sizeof(char) was 1.

Obj C code looks like it has precomputed some split points, while the C code seeks them in each iteration. Simple answer? If N is the length of buf and M the number of your split points, it looks like your two snippets have complexities of O(M) versus O(N*M); which one's slower?

edit: Really amazed me though, that some would think C code is axiomatically faster than any other solution.

Vectorization can be used to speed up C code.

Example:

Even faster UTF-8 character counting

(But maybe just try to avoid the function call strchr() in the loop condition.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM