473,785 Members | 2,824 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

homegrown string class optimisation

bob
Hi,

I'm looking at a legacy string class thats been in use here for a while
and I'd like to check out any options available to optimise it. I see a
couple of constructors that look dubious. Consider the following ctor.
It constructs a TtkString object with a string value of the integer
contained withing. e.g

TtkString one(456);
cout << one << endl;

prints;

456

// "string" is declared as a const char* within the class
TtkString::TtkS tring(int i)
{

std::stringstre am s;
s << i << std::ends;
std::string myString = s.str();
const char* localString = myString.c_str( );
int size(strlen(loc alString));
string = (char *) malloc((size + 1)*sizeof(char) ) ;
memset(string,0 ,size+1);
strncpy(string, localString,siz e);

}

reading the code below I see that stringstreams are used (which seems
to me to be a bit heavyweight) and in addition a std::string is
constructed just to get the resulting const char*, subsequently the
malloc is done followed by a memset and a strcpy. It all seems a little
heavy to me (but I stand open to correction...pe rhaps this is not such
a bad approach altogether).
I was considering using something like this for the body of the same
function....

string = (char*) calloc (1, 33); // 32 bit system assumed.
memset(string,0 ,33);
itoa(i, string, 10);
however this is not working....Ive obviously messed something up. Can
anybody shed some light? My approach allocates 33 bytes regardless of
what the "i" argument is... e.g if its 1 then I don't need all 33
bytes, do I really?

If there are examples of this implemented in some library such as boost
or whatever, I'd be keen to check them out to see how they do it and
where my mistake is.

Finally, this constructor is overloaded to take floats, doubles , longs
etc and they all work more or less on the same approach. If I can
optimise this, I can optimise them all.

thanks for any assistance/input.

have a nice day.

G

Oct 19 '06 #1
3 2123
bo*@blah.com wrote:
Hi,

I'm looking at a legacy string class thats been in use here for a while
and I'd like to check out any options available to optimise it. I see a
couple of constructors that look dubious. Consider the following ctor.
It constructs a TtkString object with a string value of the integer
contained withing. e.g

TtkString one(456);
cout << one << endl;

prints;

456
Constructors that accept a single, int parameter are usually best
declared "explicit". Otherwise, the implicit conversions - especially
from 0 - can be unexpected.
// "string" is declared as a const char* within the class
TtkString::TtkS tring(int i)
{

std::stringstre am s;
s << i << std::ends;
std::string myString = s.str();
const char* localString = myString.c_str( );
int size(strlen(loc alString));
string = (char *) malloc((size + 1)*sizeof(char) ) ;
memset(string,0 ,size+1);
strncpy(string, localString,siz e);

}
First, "string" is poor choice for a member name - especially of a
string class that uses std::string's to some extent. So I would
redeclare the member variable to be a std::string and give it a
different name.

Now concerning the current implementation: this constructor starts out
OK. Granted, stringstream is a bit heavyweight. On the other hand, C++
is not blessed with an over abundance of convenient routines for
converting between numbers and strings. And none other than Bjarne
himself recommends using stringstream for this purpose. Now, I would be
much more concerned about the sudden, nightmarish turn for the worse
that the constructor takes, managing to call malloc(), memset(),
strncpy() - a veritable rogue's gallery of C's unsized, untyped
operations that have no business threatening our C++ code.
I was considering using something like this for the body of the same
function....

string = (char*) calloc (1, 33); // 32 bit system assumed.
memset(string,0 ,33);
itoa(i, string, 10);
First, itoa() is a non-standard routine. Furthermore, since calloc()
returns zero-initialized memory there is no point in zeroing out the
memory a second time. And what is the rationale for the magic number
33? Generally choosing a power of two would make a lot more sense given
that computers are binary machines. Besidss, a 33 digit number is a bit
excessive. I am not sure whether even a 128-bit long double has that
many digits of precision.

I would just stick with the std::stringstre am and copy its std::string
to a std::string member variable (replacing the const char pointer) as
mentioned above. If you do decide to replace stringstream, then I would
use a standard routine with a sized, character buffer, such as
snprintf(), and then copy the buffer into a std::string.
however this is not working....Ive obviously messed something up. Can
anybody shed some light? My approach allocates 33 bytes regardless of
what the "i" argument is... e.g if its 1 then I don't need all 33
bytes, do I really?
The best idea is to delegate memory handling chores to a class object
like std::string. There is no other change worth making until all of
the calls to malloc, memset, memcpy and their ilk have been eliminated
by one means or another.

Greg

Oct 19 '06 #2
"bo*@blah.c om" <Gr**********@g mail.comwrote:
I'm looking at a legacy string class thats been in use here for a while
and I'd like to check out any options available to optimise it. I see a
couple of constructors that look dubious. Consider the following ctor.
It constructs a TtkString object with a string value of the integer
contained withing. e.g

TtkString one(456);
cout << one << endl;

prints;

456

// "string" is declared as a const char* within the class
TtkString::TtkS tring(int i)
{

std::stringstre am s;
s << i << std::ends;
std::string myString = s.str();
const char* localString = myString.c_str( );
int size(strlen(loc alString));
string = (char *) malloc((size + 1)*sizeof(char) ) ;
memset(string,0 ,size+1);
strncpy(string, localString,siz e);

}
Seems there is a lot of unnecessary use of temps:

std::stringstre am s;
s << i;
string = new char[s.str().length( ) + 1];
strcpy( string, s.str().c_str() );

The above accomplishes the same thing, in the same way with half the
code. Makes things much easer to understand IMHO.

I have to wonder though, TtkString is far from legacy if it uses
std::string inside itself. Just make it a Adaptor for std::string
instead. I.E.:

class TtkString {
std::string rep;
public:
// member-functions just delegate calls to std::string
// possibly making some modifications along the way
};
reading the code below I see that stringstreams are used (which seems
to me to be a bit heavyweight) and in addition a std::string is
constructed just to get the resulting const char*, subsequently the
malloc is done followed by a memset and a strcpy. It all seems a little
heavy to me (but I stand open to correction...pe rhaps this is not such
a bad approach altogether).
I was considering using something like this for the body of the same
function....

string = (char*) calloc (1, 33); // 32 bit system assumed.
memset(string,0 ,33);
itoa(i, string, 10);
however this is not working....Ive obviously messed something up. Can
anybody shed some light?
I don't have itoa, maybe if you could shed some light as to what is not
working about it?

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 19 '06 #3
bo*@blah.com wrote:
[snip]
thanks for any assistance/input.
You may be interested in Alexandrescu's article on building custom
string classes:

http://www.ddj.com/dept/cpp/184403784

The code from that article became flex_string in the Loki library,
which can be found here:

http://sourceforge.net/projects/loki-lib/

Cheers! --M

Oct 19 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
5770
by: Java script Dude | last post by:
In many languages, it is necessary to string together multiple strings into one string for use over multiple lines of code. Which one is the most efficient from the interpreters perspective: Case 1: str += '<?xml version="1.0" encoding="' + charset + '"?>\n'; str += '<view-source-with version="1.1">\n'; str += ' <default-item-index>' + this.defaultItem + '</default-item-index>\n';
7
2756
by: Philip Nelson | last post by:
Folks, I've been exercising my mind recently about the complexities of implementing a "currency" data type within DB2 to cope with multiple currencies. A monetary value is often simply represented as a DECIMAL column : for example many times I've seen DECIMAL(12,2) used. The issue with this is that there is nothing to interpret what currency this relates to (US dollars, Canadian dollars, Euros, British pounds or whatever), and a...
19
78838
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not find one.
0
2063
by: Brent Clements | last post by:
I have been trying to determine the best way to setup a directory structure for my homegrown MVC application. What do you guys suggest? I am thinking about doing the following: | +-- app
46
2150
by: Albert | last post by:
Why doesn't: #include <stdio.h> void reverse(char, int); main() { char s;
33
4691
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
17
2831
by: mac | last post by:
Hi, I'm trying to write a fibonacci recursive function that will return the fibonacci string separated by comma. The problem sounds like this: ------------- Write a recursive function that creates a character string containing the first n Fibonacci numbers - F(n) = F(n - 1) + F(n - 2), F(0) = F(1) = 1 -, separated by comma. n should be given as an argument to the program. The recursive function should only take one parameter, n, and...
12
4292
by: Avalon1178 | last post by:
Hi, I have an application that periodically uses a std::string variable which is assigned a VERY VERY large string (15000000+ bytes long). This application is essentially a daemon, and it polls a data set which can have a lot of information and it is concatenated in this single string variable object. When the daemon finishes its job, it goes to sleep, but before doing so, it "clears" this variable so it can be reused again in the next...
11
4023
by: Dan Holmes | last post by:
I have a need to reverse a date to show as a "date code". For example today, 090507 would be coded as 905070 (reversing the parts of the date. This is what i have but there has to be a better way. DateTime d = DateTime.Now; string datecodemonth = d.ToString("MM"); datecodemonth = datecodemonth + datecodemonth; string datecodeday = d.ToString("dd"); datecodeday = datecodeday + datecodeday;
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.