开发者

Which is efficient, itoa or sprintf?

I am in the processes of building my first C++ application and choosing an efficient C++ libraries to rely on at this stage, is one of the design consideration I am looking at.

Consequently I want to convert an integer type to string and deciding on whether to use;

sprintf(string, "%d", x);

Or

Integer 开发者_如何学Cto ASCI

itoa(x, string);

Can anyone suggest which one of these route is efficient and possibly why?

Thanks.


They're both efficient. It's probably much more relevant to note that itoa() is not part of the C++ standard, and as such is not available in many common runtimes. (In particular, it's not part of libstdc++, so it's not available on Mac OS X or Linux.)


Don't use either of these. Use std::stringstream and so on.

std::stringstream ss;
ss << x;
ss.str();  // Access the std::string

Either way, it's quite unlikely that converting to string will be a significant part of your application's execution time.


From a pure algorithm viewpoint one can argue that itoa would be faster since sprintf has the additional cost of parsing the format descriptor string. However without benchmarking the cost of the two functions in an implementation, with a non-trivial work load, one cannot be sure.

Also this isn't apples to apples comparison since both functions aren't equivalent. sprintf can do much more formatting than itoa does, apart from the fact that the former is a standard function while the latter isn't.

Aside: If you can use C++11 you can use to_string which returns you an std::string. If you want representations other than decimal you may do this:

int i = 1234;
std::stringstream ss;
ss << std::hex << i;       // hexadecimal
ss << std::oct << i;       // octal
ss << std::dec << i;       // decimal

std::bitset<sizeof(int) * std::numeric_limits<unsigned char>::digits> b(i);
ss << b;                   // binary

std::string str = ss.str();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜