title: What's the fastest way to init a NSString from a CString?
body: <p>I need to allocate lot's of NSString objects from cStrings (which come that way from a database), as fast as possible. cStringUsingEncoding and the likes are just too slow - about 10-15 times slower compared to allocating a cString. </p>
  
  <p>However, creating a NSString with a NSString is getting pretty close to cString allocation (about 1.2s for 1M allocations). EDIT: Fixed alloc to use a copy of the string. </p>
  
  <pre><code>const char *n;
  const char *s = "Office für iPad: Steve Ballmer macht Hoffnung";
  NSString *str = [NSString stringWithUTF8String:s];
  int len = strlen(s);
  for (int i = 0; i&lt;10000000; i++) {
      NSString *s = [[NSString alloc] initWithString:[str copy]];
      s = s;
  }
  </code></pre>
  
  <p>cString allocation test (also about 1s for 1M allocations):</p>
  
  <pre><code>for (int i = 0; i&lt;10000000; i++) {
      n = malloc(len);
      memccpy((void*)n, s, 0, len) ;
      n = n;
      free(n);
  }
  </code></pre>
  
  <p>But as I said, using stringWithCString and the likes is an order of magnitude slower. The fastest I could get was using initWithBytesNoCopy (about 8s, therefore 8 times slower compared to stringWithString):</p>
  
  <pre><code>NSString *so = [[NSString alloc] initWithBytesNoCopy:(void*)n length:len encoding:NSUTF8StringEncoding freeWhenDone:YES];
  </code></pre>
  
  <p>So, is there another magic way to make allocations from cStrings faster? I'd even not rule out to subclass NSString (and yes, I know it's a cluster class).</p>
  
  <p>EDIT: In instruments I see that NSString's call to CFStringUsingByteStream3 is the root issue.  </p>
  
  <p>EDIT 2: The root issue is according to instuments __CFFromUTF8. Just looking at the sources [1], this seems indeed to be quite inefficient and handling some legacy cases. </p>
  
  <p><a href="https://www.opensource.apple.com/source/CF/CF-476.17/CFBuiltinConverters.c?txt" rel="nofollow">https://www.opensource.apple.com/source/CF/CF-476.17/CFBuiltinConverters.c?txt</a></p>