473,789 Members | 2,106 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 1654
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
2981
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
12774
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
20590
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
2502
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
2704
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
1513
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
1262
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
9659
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
9504
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
9977
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9011
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6754
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
5413
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5545
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4084
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
2903
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.