Automatic Java to C++ conversion

Jiayao Yu picture Jiayao Yu · Jul 8, 2009 · Viewed 8.8k times · Source

Has anyone tried automatic Java to C++ conversion for speed improvements? Is it a maintenance nightmare in the long run? Just read that is used to generate the HTML5 parsing engine in Gecko http://ejohn.org/blog/html-5-parsing/

Answer

In general, automatic conversions from one language to another will not be an improvement. Different languages have different idioms that affect performance.

The simplest example is with loops and variable creation. In a Java GC world, creating objects with new is almost free, and they dive into oblivion just as easily. In C++ memory allocation is (generally speaking) expensive:

// Sample java code
for ( int i = 0; i < 10000000; ++i )
{
   String str = new String( "hi" ); // new is free, GC is almost free for young objects
}

Direct conversion to C++ will result in bad performance (use of TR1 shared_ptr as memory handler instead of GC):

for ( int i = 0; i < 10000000; ++i )
{
   std::shared_ptr< std::string > str( new std::string( "hi" ) );
}

The equivalent loop written in C++ would be:

for ( int i = 0; i < 10000000; ++i )
{
   std::string str( "hi" );
}

Direct translation from a language to another usually ends with the worst of both worlds and harder to maintain code.