473,776 Members | 2,074 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A program that writes code: should it use 'string'?


I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?

The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?

TIA,

-RFH
-------------

void SynthesizeTextF ield(CompleteFi eld fullTextField)
{
string code;
string baseFieldname = "text";
stringstream ss;
static int subindex = 1;

code = "Field ";
code += baseFieldname;
ss << subindex;
code += ss.str();
code += " ";
code += "doc.FieldCreat e(\"";
code += baseFieldname;
code += ss.str();
code += "\", Field::e_text, \"\", \"\");";

subindex++;
}
Jun 27 '08 #1
13 1650
Ramon F Herrera wrote:
>
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?

Recommended is to measure before you optimize. Write the program so that it
is easy to understand. When (and only when) you have a performance problem,
don't guess what the cause might be; instead, use a profiler to identify
the bottleneck and then do something about it.

The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?
[snip]

If profiling shows that appending to the string is too costly, reserving a
certain capacity would be the first thing to try. It's the least intrusive
measure.
Best

Kai-Uwe Bux
Jun 27 '08 #2
Ramon F Herrera <ra***@conexus. netwrote:
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?

The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?
A std::string is just a vector<charwith some extra functions that you
probably don't need for this particular variable.

I think your best bet would be to make your own class to represent
"code", implement that class with a string if that makes sense to you.
The nice thing is you can always change the implementation of the class
later as profiling requires, without affecting any other code.
Jun 27 '08 #3
On Jun 1, 11:58 pm, Ramon F Herrera <ra...@conexus. netwrote:
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?
The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?
-------------
void SynthesizeTextF ield(CompleteFi eld fullTextField)
{
string code;
string baseFieldname = "text";
stringstream ss;
static int subindex = 1;

code = "Field ";
code += baseFieldname;
ss << subindex;
code += ss.str();
code += " ";
code += "doc.FieldCreat e(\"";
code += baseFieldname;
code += ss.str();
code += "\", Field::e_text, \"\", \"\");";

subindex++;
}
For starters, I'd generate (or support generation) directly into
the output stream. Something like:

std::ostream&
SynthesizeTextF ield(
std::ostream& dest,
... )
{
// ...
return dest ;
}

You're formatting here (some of the data is numeric,
apparently), so you might as well treat the entire thing as a
stream. And you'll certainly be outputting it in the end;
there's not much you can do with C++ source code within the
program, so you might as well generate directly into the output
stream, and never build the string at all.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #4
Ramon F Herrera wrote:
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?
I think it's ok. You could also say something like
"code.reserve(1 00*1024);" which allocates 100kB (or any other
amount you feel is about correct) of memory for it so that it
never has to resize (unless you exceed that limit, of course),
which might make it slightly more efficient.
Jun 27 '08 #5
Ramon F Herrera <ra***@conexus. netwrites:
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?

The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?
[...]
code += "doc.FieldCreat e(\"";
[...]
No, you should not use strings to generate code. Code is a syntac
tree. You should have a tree of objects:

Lhs* lhs=new Variable("pi_sq uared");
Rhs* rhs=new Variable("pi");
Statement* code=new Assignment(lhs, new Multiply(rhs,rh s));
cout<<code->generate();

would produce:

pi_squared=pi*p i;
--
__Pascal Bourguignon__
Jun 27 '08 #6
In article <7c************ @pbourguignon.a nevia.com>,
Pascal J. Bourguignon <pj*@informatim ago.comwrote:
>
No, you should not use strings to generate code. Code is a syntac
tree. You should have a tree of objects:

Lhs* lhs=new Variable("pi_sq uared");
Rhs* rhs=new Variable("pi");
Statement* code=new Assignment(lhs, new Multiply(rhs,rh s));
cout<<code->generate();
This is C++, not Java, loose the "new" abuse:
// class Variable;
// class Statement;
// class Assignment: public Statement;

Variable lhs("pi_squared ");
Variable rhs("pi");
Assignment code(lhs, Multiply(rhs, rhs);

cout << code.generate() ;

// or
cout << Assignement(Var iable("pi_squar ed"),
Multiply(Variab le("pi"),Variab le("pi")).gener ate();
>would produce:

pi_squared=pi*p i;
Your tree of object approach is probably superior as complexity
increases. For simple problems direct construction in a
string/ostream is likely to be sufficient but if you have a lot of
complex code generation to do, the cost of creating the code object
hierarchy is likely to be worthwhile.

Yannick

Jun 27 '08 #7
On Jun 2, 2:38 pm, p...@informatim ago.com (Pascal J. Bourguignon)
wrote:
Ramon F Herrera <ra...@conexus. netwrites:
I am writing a program that generates source code. See a snippet
below. My question is about the use of that growing 'code' variable.
Is it efficient? Is is recommended for this case?
The code generated can grow a lot. Perhaps I should allocate a large
max size in advance?
[...]
code += "doc.FieldCreat e(\"";
[...]
No, you should not use strings to generate code. Code is a
syntac tree.
That depends a lot on the code. The compiler may treat it as a
syntax tree, but most of the time I'm generating code, it's
fairly flat (tables and that sort of stuff). And of course, in
the end, you need text, to feed to the compiler.
You should have a tree of objects:

Lhs* lhs=new Variable("pi_sq uared");
Rhs* rhs=new Variable("pi");
Statement* code=new Assignment(lhs, new Multiply(rhs,rh s));
cout<<code->generate();
would produce:
pi_squared=pi*p i;
I think you've missed the question. The original poster may
actually be already doing that, for all we know. The question
concerned the generation of the code, not the source from which
it was generated. And the code itself must be text (at least as
the question was posed).

Of course, I agree that you don't have to generate that text
entirely in one std::string object. Regardless of the source,
you should (usually) output it directly to an ostream (which
could be an ostringstream *if* you need the text in the process,
but usually, it will be an ofstream, I think).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #8
On Jun 2, 3:41 pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
In article <7clk1oc8r6.... @pbourguignon.a nevia.com>,
Pascal J. Bourguignon <p...@informati mago.comwrote:
No, you should not use strings to generate code. Code is a syntac
tree. You should have a tree of objects:
Lhs* lhs=new Variable("pi_sq uared");
Rhs* rhs=new Variable("pi");
Statement* code=new Assignment(lhs, new Multiply(rhs,rh s));
cout<<code->generate();
This is C++, not Java, loose the "new" abuse:
He's building a tree. That pretty much required dynamic
allocation.
// class Variable;
// class Statement;
// class Assignment: public Statement;
Variable lhs("pi_squared ");
Variable rhs("pi");
Assignment code(lhs, Multiply(rhs, rhs);
Unless you've got dynamic allocation of the nodes somewhere
hidden in the constructors, this is not going to work. And of
course, it doesn't work if the expression is the result of
parsing some external data either.
cout << code.generate() ;
// or
cout << Assignement(Var iable("pi_squar ed"),
Multiply(Variab le("pi"),Variab le("pi")).gener ate();
would produce:
pi_squared=pi*p i;
Your tree of object approach is probably superior as
complexity increases. For simple problems direct construction
in a string/ostream is likely to be sufficient but if you have
a lot of complex code generation to do, the cost of creating
the code object hierarchy is likely to be worthwhile.
Tree or not, you'll have to either build a string or generate
text directly into an ostream sooner or later. If I understand
the original poster correctly, his question concerned the
efficiency of using a string when the size of the code became
large; he's already solved his problem the source of the code
(tree or otherwise).

I'll admit that I generate a lot of code automatically, and I've
never used a syntax tree to do so. But most of the code is just
tables, or a function with a single switch statement (which is
also a table of sorts). Or the code is generated from a
template (general sense of the word, not a C++ template).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
Pascal J. Bourguignon wrote:
No, you should not use strings to generate code. Code is a syntac
tree. You should have a tree of objects:
Why make things more complicated than necessary? You converted his
easy-to-read code into a mess of pointers and dynamically allocated
objects. What for?
Jun 27 '08 #10

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

Similar topics

3
2980
by: Mahmood Ahmad | last post by:
Hello, I have written a program that reads three types of records, validates them acording to certain requirements and writes the valid records into a binary file. The invalid records are supposed to be reported on the printer but I have commented those pieces of code and have got those records printed on the screen. I am using Microsoft Visual C++ 6.0 on Microsoft XP (Home) platform. I am facing some problems in getting desire...
7
12773
by: Zack Wahab | last post by:
Hi, I use Dev C++ compiler. Tried this program : // Fig. 1.6: fig01_06.cpp // Addition program. #include <iostream> // function main begins program execution int main()
10
1893
by: Robert Rotstein | last post by:
Following is a C program, taken from http://en.wikipedia.org/wiki/Quine#Sample_quine_in_C, which has the curious property that, when executed, it produces its own source code as output. #include <stdio.h> char x="#include <stdio.h>%cchar x=%c%s%c;%cint main() {printf(x,10,34,x,34,10,10);return 0;}%c"; int main() {printf(x,10,34,x,34,10,10);return 0;}
19
20587
by: linzhenhua1205 | last post by:
I want to parse a string like C program parse the command line into argc & argv. I hope don't use the array the allocate a fix memory first, and don't use the memory allocate function like malloc. who can give me some ideas? The following is my program, but it has some problem. I hope someone would correct it. //////////////////////////// //Test_ConvertArg.c ////////////////////////////
3
2500
by: Nijazi Halimaji | last post by:
Hi I know that what I am asking for is very simple, but as a newbie in VB.NET i have following 2 questions: Eigentlich ist das ja etwas ganz einfaches, aber für mich als VB.NET-Neuling doch etwas komplizierter. 1. How can I read and write value from / into a ini-file?
41
2701
by: c | last post by:
Hi every one, Me and my Cousin were talking about C and C#, I love C and he loves C#..and were talking C is ...blah blah...C# is Blah Blah ...etc and then we decided to write a program that will calculate the factorial of 10, 10 millions time and print the reusult in a file with the name log.txt.. I wrote something like this
6
1512
by: =?iso-8859-1?q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Usually someone writes a program and guarantees its behaviour so long as people don't deliberately go and try to make it malfunction. For instance, let's say we have a "Proceed" button on the dialog box, but that this button is greyed out because the user hasn't entered their username yet. Now let's say the user writes some code that sends a message to the dialog box to enable the "Proceed" button even tho the programmer didn't design...
4
224
by: Ramon F Herrera | last post by:
I am writing a program that generates source code. See a snippet below. My question is about the use of that growing 'code' variable. Is it efficient? Is is recommended for this case? The code generated can grow a lot. Perhaps I should allocate a large max size in advance? TIA, -RFH
6
1259
by: mcse jung | last post by:
Here is asample program that writes a program and then executes it. Do you knowof a much simpler way of writing a program that writes a program? """ ----------------------------------------------------------------------------- Name: _writePythonCode.py Purpose: This script writes Python code and thentransfers control to it. Author: MCSEJUNG
0
9625
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
9459
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
10282
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...
0
10117
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10056
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
7467
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
6721
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();...
1
4027
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
2
3619
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.