• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 10:46
CEST 16:46
KST 23:46
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL21] Ro24 Preview Pt1: New Chaos0Team Liquid Map Contest #22 - Presented by Monster Energy9ByuL: The Forgotten Master of ZvT30Behind the Blue - Team Liquid History Book20Clem wins HomeStory Cup 289
Community News
Weekly Cups (March 16-22): herO doubles, Cure surprises3Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool48Weekly Cups (March 9-15): herO, Clem, ByuN win42026 KungFu Cup Announcement6BGE Stara Zagora 2026 cancelled12
StarCraft 2
General
Team Liquid Map Contest #22 - Presented by Monster Energy What mix of new & old maps do you want in the next ladder pool? (SC2) Potential Updates Coming to the SC2 CN Server Behind the Blue - Team Liquid History Book herO wins SC2 All-Star Invitational
Tourneys
RSL Season 4 announced for March-April Sparkling Tuna Cup - Weekly Open Tournament StarCraft Evolution League (SC Evo Biweekly) WardiTV Mondays World University TeamLeague (500$+) | Signups Open
Strategy
Custom Maps
[M] (2) Frigid Storage Publishing has been re-enabled! [Feb 24th 2026]
External Content
The PondCast: SC2 News & Results Mutation # 518 Radiation Zone Mutation # 517 Distant Threat Mutation # 516 Specter of Death
Brood War
General
Pros React To: SoulKey vs Ample ASL21 General Discussion RepMastered™: replay sharing and analyzer site KK Platform will provide 1 million CNY Recent recommended BW games
Tourneys
[ASL21] Ro24 Group C [Megathread] Daily Proleagues [ASL21] Ro24 Group B [ASL21] Ro24 Group A
Strategy
What's the deal with APM & what's its true value Fighting Spirit mining rates Simple Questions, Simple Answers
Other Games
General Games
General RTS Discussion Thread Nintendo Switch Thread Stormgate/Frost Giant Megathread Darkest Dungeon Path of Exile
Dota 2
The Story of Wings Gaming Official 'what is Dota anymore' discussion
League of Legends
G2 just beat GenG in First stand
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Five o'clock TL Mafia Mafia Game Mode Feedback/Ideas Vanilla Mini Mafia
Community
General
US Politics Mega-thread The Games Industry And ATVI European Politico-economics QA Mega-thread Canadian Politics Mega-thread Russo-Ukrainian War Thread
Fan Clubs
The IdrA Fan Club
Media & Entertainment
[Manga] One Piece [Req][Books] Good Fantasy/SciFi books Movie Discussion!
Sports
Formula 1 Discussion 2024 - 2026 Football Thread Cricket [SPORT] Tokyo Olympics 2021 Thread General nutrition recommendations
World Cup 2022
Tech Support
[G] How to Block Livestream Ads
TL Community
The Automated Ban List
Blogs
Funny Nicknames
LUCKY_NOOB
Money Laundering In Video Ga…
TrAiDoS
Iranian anarchists: organize…
XenOsky
FS++
Kraekkling
Shocked by a laser…
Spydermine0240
ASL S21 English Commentary…
namkraft
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1064 users

The Big Programming Thread - Page 233

Forum Index > General Forum
Post a Reply
Prev 1 231 232 233 234 235 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
heishe
Profile Blog Joined June 2009
Germany2284 Posts
Last Edited: 2013-01-26 00:51:26
January 26 2013 00:48 GMT
#4641
On January 26 2013 09:30 Zeke50100 wrote:
This isn't premature optimization at all.


Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this.

Example code:




#include <iostream>

struct vec2
{
int x,y;
};

vec2 operator+(const vec2& a, const vec2&b)
{
vec2 result;
result.x = a.x + b.x;
result.y = a.y + b.y;
return result;
}

int main()
{
int x,y;
vec2 a,b,c,d;

std::cin>>x; std::cin>>y;
a.x = x; a.y = y;
std::cin>>x; std::cin>>y;
b.x = x; b.y = y;
std::cin>>x; std::cin>>y;
c.x = x; c.y = y;
std::cin>>x; std::cin>>y;
d.x = x; d.y = y;

a = a+b+c+d;

std::cout<<a.x<<" "<<a.y<<std::endl;
return 0;
}


compiled with the compiler in VS2005 (remember that compiler is 7+ years old) yields (for the relevant section)

00221328 mov ecx,dword ptr [esp+18h]
0022132C add ecx,dword ptr [esp+1Ch]
00221330 mov edx,dword ptr [esp+14h]
00221334 mov eax,dword ptr [esp+10h]

std::cout<<a.x<<" "<<a.y<<std::endl;
00221338 push dword ptr ds:[223044h]
d.x = x; d.y = y;

a = a+b+c+d;
0022133E add edx,ebx
00221340 add ecx,edi
00221342 add edx,esi
00221344 add edx,dword ptr [esp+10h]
00221348 add eax,ecx

//right here there would be movs back to memory but the compiler doesn't do that and instead uses the registersto print to cout


Please show me how this can be rewritten to use less registers and/or addresses on the stack . Or point out the additional variable "somewhere in the middle". I'd be very surprised if GCC produces worse code than that.

Complete disassembly in spoilers:

+ Show Spoiler +

int main()
{
00221270 push ebp
00221271 mov ebp,esp
00221273 and esp,0FFFFFFF8h
00221276 sub esp,14h
int x,y;
vec2 a,b,c,d;

std::cin>>x; std::cin>>y;
00221279 mov ecx,dword ptr ds:[223058h]
0022127F push ebx
00221280 push esi
00221281 push edi
00221282 lea eax,[esp+0Ch]
00221286 push eax
00221287 call dword ptr ds:[22302Ch]
0022128D mov ecx,dword ptr ds:[223058h]
00221293 lea eax,[esp+10h]
00221297 push eax
00221298 call dword ptr ds:[22302Ch]
a.x = x; a.y = y;
0022129E mov eax,dword ptr [esp+0Ch]
std::cin>>x; std::cin>>y;
002212A2 mov ecx,dword ptr ds:[223058h]
002212A8 mov dword ptr [esp+14h],eax
002212AC mov eax,dword ptr [esp+10h]
002212B0 mov dword ptr [esp+1Ch],eax
002212B4 lea eax,[esp+0Ch]
002212B8 push eax
002212B9 call dword ptr ds:[22302Ch]
002212BF mov ecx,dword ptr ds:[223058h]
002212C5 lea eax,[esp+10h]
002212C9 push eax
002212CA call dword ptr ds:[22302Ch]
b.x = x; b.y = y;
002212D0 mov eax,dword ptr [esp+10h]
std::cin>>x; std::cin>>y;
002212D4 mov ecx,dword ptr ds:[223058h]
002212DA mov ebx,dword ptr [esp+0Ch]
002212DE mov dword ptr [esp+18h],eax
002212E2 lea eax,[esp+0Ch]
002212E6 push eax
002212E7 call dword ptr ds:[22302Ch]
002212ED mov ecx,dword ptr ds:[223058h]
002212F3 lea eax,[esp+10h]
002212F7 push eax
002212F8 call dword ptr ds:[22302Ch]
c.x = x; c.y = y;
std::cin>>x; std::cin>>y;
002212FE mov ecx,dword ptr ds:[223058h]
00221304 mov esi,dword ptr [esp+0Ch]
00221308 mov edi,dword ptr [esp+10h]
0022130C lea eax,[esp+0Ch]
00221310 push eax
00221311 call dword ptr ds:[22302Ch]
00221317 mov ecx,dword ptr ds:[223058h]
0022131D lea eax,[esp+10h]
00221321 push eax
00221322 call dword ptr ds:[22302Ch]
d.x = x; d.y = y;

a = a+b+c+d;
00221328 mov ecx,dword ptr [esp+18h]
0022132C add ecx,dword ptr [esp+1Ch]
00221330 mov edx,dword ptr [esp+14h]
00221334 mov eax,dword ptr [esp+10h]

std::cout<<a.x<<" "<<a.y<<std::endl;
00221338 push dword ptr ds:[223044h]
d.x = x; d.y = y;

a = a+b+c+d;
0022133E add edx,ebx
00221340 add ecx,edi
00221342 add edx,esi
00221344 add edx,dword ptr [esp+10h]
00221348 add eax,ecx

std::cout<<a.x<<" "<<a.y<<std::endl;
0022134A mov ecx,dword ptr ds:[22305Ch]
00221350 push eax
00221351 push edx
00221352 call dword ptr ds:[223034h]
00221358 mov ecx,eax
0022135A call std::operator<<<std::char_traits<char> > (0221810h)
0022135F mov ecx,eax
00221361 call dword ptr ds:[223034h]
00221367 mov ecx,eax
00221369 call dword ptr ds:[223038h]
return 0;
}
0022136F pop edi
00221370 pop esi
00221371 xor eax,eax
00221373 pop ebx
00221374 mov esp,ebp
00221376 pop ebp
00221377 ret
If you value your soul, never look into the eye of a horse. Your soul will forever be lost in the void of the horse.
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2013-01-26 01:11:22
January 26 2013 01:07 GMT
#4642
Do you really want to suffer the drawback of creating tons of temporary objects just to make it look prettier?

Ask yourself few months into the development.

Stack allocation of temporary objects is like, an addition to the stack pointer, followed by assignment into those stack addresses, which are almost always in the cache. Or into the registers.

With far away re-used variables, additional pointer parameters, heap allocation, or other tricks to get around temporary objects, you are only making things worse. Both performance and clarity wise.

If you are really that worried about temporary objects, use the move semantics found in C++11. It solves most of the worries about temporary objects.

What about more complicated objects, when you're suddenly tossing around the stack like a ragdoll due to the sheer size of every object?

Consider moving out said complicated objects to the heap, it has like 100 times as much capacity, and is more friendly to polymorphic objects.

if anything, having both the helper function and the operator would be preferred

Only keep one, you are only making the maintenance harder.

Few advices that come to my mind:
- Do not use comments, especially not as compensation for illegible code. They are only noise in the code, they are always outdated, hard to read, or outright lying.
- Code cleanly, with the most appropriate tools and constructs you have, don't hack your way around perceived problems, don't reinvent the wheel. Chances are, it is already solved on some level; compiler optimization, language extension, library, etc.
- These tools include the features provided by the language. They are there for a reason, use them when they are appropriate.
- Don't reuse variables, it's like the most uglies way to mess up your code.
- Think about the lifetime of objects and allocate them on the stack or on the heap accordingly.
- Don't optimize prematurely. Worry about performance only when you actually have a well-tested, end-to-end working software and you can actually measure its bottlenecks. You can be surprised about the lack of obvious bottlenecks.
- Read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. This is the book that introduced me to clean code, TDD, refactoring and code quality, and it does a very good job at explaining why is it important.
- Code in Java for a few months with Eclipse. Your perspective and your C++ skills will improve.
http://www.fimfiction.net/user/Treasure_Chest
mcc
Profile Joined October 2010
Czech Republic4646 Posts
January 26 2013 01:20 GMT
#4643
On January 26 2013 10:07 Frigo wrote:
Show nested quote +
Do you really want to suffer the drawback of creating tons of temporary objects just to make it look prettier?

Ask yourself few months into the development.

Stack allocation of temporary objects is like, an addition to the stack pointer, followed by assignment into those stack addresses, which are almost always in the cache. Or into the registers.

With far away re-used variables, additional pointer parameters, heap allocation, or other tricks to get around temporary objects, you are only making things worse. Both performance and clarity wise.

If you are really that worried about temporary objects, use the move semantics found in C++11. It solves most of the worries about temporary objects.

Show nested quote +
What about more complicated objects, when you're suddenly tossing around the stack like a ragdoll due to the sheer size of every object?

Consider moving out said complicated objects to the heap, it has like 100 times as much capacity, and is more friendly to polymorphic objects.

Show nested quote +
if anything, having both the helper function and the operator would be preferred

Only keep one, you are only making the maintenance harder.

Few advices that come to my mind:
- Do not use comments, especially not as compensation for illegible code. They are only noise in the code, they are always outdated, hard to read, or outright lying.
- Code cleanly, with the most appropriate tools and constructs you have, don't hack your way around perceived problems, don't reinvent the wheel. Chances are, it is already solved on some level; compiler optimization, language extension, library, etc.
- These tools include the features provided by the language. They are there for a reason, use them when they are appropriate.
- Don't reuse variables, it's like the most uglies way to mess up your code.
- Think about the lifetime of objects and allocate them on the stack or on the heap accordingly.
- Don't optimize prematurely. Worry about performance only when you actually have a well-tested, end-to-end working software and you can actually measure its bottlenecks. You can be surprised about the lack of obvious bottlenecks.
- Read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. This is the book that introduced me to clean code, TDD, refactoring and code quality, and it does a very good job at explaining why is it important.
- Code in Java for a few months with Eclipse. Your perspective and your C++ skills will improve.

To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ?
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2013-01-26 02:05:22
January 26 2013 02:02 GMT
#4644
On January 26 2013 10:20 mcc wrote:
To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ?

Well, C++ lacks a lot of comfort features, leaves a lot of behavior undefined, keeps unneeded C compatibility features, and for any given thing, there is at least 3 ways to do it, all with their own set of problems and annoying details. This makes casual coding in it pretty difficult.

In Java on the other hand, the language has more integrity and is more modern, standard libraries cover more territory, library support is better, IDEs are easier to use, etc. You need less effort to start coding in it and can focus more on the design and structure of your program, rather than trying to understand and struggle with peculiar aspects of the language. You focus more on programming itself and keep improving the software engineer in you.

Then when (if) you return to C++, you will have a true high-level perspective on C++, instead of a low-level, C perspective. Suddenly the language features and the flexibility start to make sense. You will no longer try to prematurely optimize performance or memory consumption, you will no longer see C++ as C-with-class-instead-of-struct-keyword, you will learn to use and value the language features, use classes and methods over primitives and functions, use stack and heap where appropriate, use pass by value, pass by pointer and pass by reference where appropriate. You will no longer write screens of unstructured code, you will use methods and objects as intended. You will get yourself rid of the annoying habits and hacks of C and bad C++.

You will be able to focus on programming itself instead of the peculiarities of the language.
http://www.fimfiction.net/user/Treasure_Chest
Zeke50100
Profile Blog Joined February 2010
United States2220 Posts
Last Edited: 2013-01-26 02:24:06
January 26 2013 02:19 GMT
#4645
On January 26 2013 09:48 heishe wrote:
Show nested quote +
On January 26 2013 09:30 Zeke50100 wrote:
This isn't premature optimization at all.


Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this.


My main concern was with the creation of temporary variables and not how many instructions would exist in the assembly.

+ Show Spoiler [Example Code] +
#include <iostream>

class vec2 {
public:
int x, y;
vec2(int _x, int _y) : x(_x), y(_y) {
std::cout << "Constructing vector at " << this << " with values " << x << " " << y << "\n";
}

//Is never called
vec2(const vec2& copy) {
std::cout << "Copy constructing vector at " << &copy << " with values " << copy.x << " " << copy.y << "\n";
}

vec2 operator+(const vec2& rhs) const {
return vec2(x + rhs.x, y + rhs.y);
}
};

void vec2Add(vec2* dest, const vec2* src1, const vec2* src2) {
dest->x = src1->x + src2->x;
dest->y = src1->y + src2->y;
}

int main()
{
vec2 a(0, 0), b(1, 1), c(2, 2), d(3, 3); //4 constructors called

vec2Add(&a, &a, &b); //a = a + b
vec2Add(&a, &a, &c); //a = a + c // a = a + b + c
vec2Add(&a, &a, &d); //a = a + d // a = a + b + c + d

std::cout << "Using vec2Add, a has values: " << a.x << " " << a.y << "\n\n";

vec2 v1(0, 0), v2(1, 1), v3(2, 2), v4(3, 3); //4 constructors called
v1 = v1 + v2 + v3 + v4;

std::cout << "Using operator+, v1 has values: " << v1.x << " " << v1.y << "\n\n";

std::cin.get();
return 0;
}


This is just a quick example to show the number of times the objects are constructed. Both parts initially create 4 vec2 objects, then perform "a = a + b + c + d" (or, in the second case, "v1 = v1 + v2 + v3 + v4"); both methods have the exact same result. What actually goes on underneath is a bit different, though:

Constructing vector at 002AFD60 with values 0 0
Constructing vector at 002AFD70 with values 1 1
Constructing vector at 002AFD78 with values 2 2
Constructing vector at 002AFD80 with values 3 3
Using vec2Add, a has values: 6 6


Constructing vector at 002AFD68 with values 0 0
Constructing vector at 002AFD88 with values 1 1
Constructing vector at 002AFD90 with values 2 2
Constructing vector at 002AFDA0 with values 3 3
Constructing vector at 002AFD98 with values 1 1
Constructing vector at 002AFDA8 with values 3 3
Constructing vector at 002AFDB0 with values 6 6
Using operator+, v1 has values: 6 6


The second method ended up with 3 additional constructions of vec2 objects. It's not exactly a fair comparison, so I quickly changed it around not to construct v1 until it's assigned a value, which reduced the number of additional constructions to 1. Still, there's at least 1 temporary variable associated with vector addition that is unnecessary.
mcc
Profile Joined October 2010
Czech Republic4646 Posts
January 26 2013 03:05 GMT
#4646
On January 26 2013 11:02 Frigo wrote:
Show nested quote +
On January 26 2013 10:20 mcc wrote:
To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ?

Well, C++ lacks a lot of comfort features, leaves a lot of behavior undefined, keeps unneeded C compatibility features, and for any given thing, there is at least 3 ways to do it, all with their own set of problems and annoying details. This makes casual coding in it pretty difficult.

In Java on the other hand, the language has more integrity and is more modern, standard libraries cover more territory, library support is better, IDEs are easier to use, etc. You need less effort to start coding in it and can focus more on the design and structure of your program, rather than trying to understand and struggle with peculiar aspects of the language. You focus more on programming itself and keep improving the software engineer in you.

Then when (if) you return to C++, you will have a true high-level perspective on C++, instead of a low-level, C perspective. Suddenly the language features and the flexibility start to make sense. You will no longer try to prematurely optimize performance or memory consumption, you will no longer see C++ as C-with-class-instead-of-struct-keyword, you will learn to use and value the language features, use classes and methods over primitives and functions, use stack and heap where appropriate, use pass by value, pass by pointer and pass by reference where appropriate. You will no longer write screens of unstructured code, you will use methods and objects as intended. You will get yourself rid of the annoying habits and hacks of C and bad C++.

You will be able to focus on programming itself instead of the peculiarities of the language.

I see what you mean. That is one way to do it. Another I think is to work on big, well-led C++ project that forces you to do the same. In general I think working on reasonably big projects (as in 10/15+ developers) for long period of time so you will also taste bugfixing issues is pretty good school how to develop good programming habits. Especially the bugfixing part teaches you a lot - ah the hours spent over stacks corrupted due to uninitialized pointers At least in my case that thought me a lot of valuable lessons on the high-level engineering side of things. And I think even if you work with Java/C# you need the experience from really big team projects to develop some of the necessary habits.
Frigo
Profile Joined August 2009
Hungary1023 Posts
January 26 2013 03:20 GMT
#4647
On January 26 2013 11:19 Zeke50100 wrote:
Still, there's at least 1 temporary variable associated with vector addition that is unnecessary.

Use += duh. No temporary objects whatsoever.

I don't understand what more do you expect. The compiler won't magically know the commutative and other properties of your addition operator to optimize away the construction of the actual result, especially after you explicitly refer to the constructor in the operator. It is smart enough however, to store them in registers, or in the cache so temporary objects become a non-issue.
http://www.fimfiction.net/user/Treasure_Chest
heishe
Profile Blog Joined June 2009
Germany2284 Posts
Last Edited: 2013-01-26 08:22:57
January 26 2013 08:21 GMT
#4648
On January 26 2013 11:19 Zeke50100 wrote:
Show nested quote +
On January 26 2013 09:48 heishe wrote:
On January 26 2013 09:30 Zeke50100 wrote:
This isn't premature optimization at all.


Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this.


My main concern was with the creation of temporary variables and not how many instructions would exist in the assembly.

+ Show Spoiler [Example Code] +
#include <iostream>

class vec2 {
public:
int x, y;
vec2(int _x, int _y) : x(_x), y(_y) {
std::cout << "Constructing vector at " << this << " with values " << x << " " << y << "\n";
}

//Is never called
vec2(const vec2& copy) {
std::cout << "Copy constructing vector at " << &copy << " with values " << copy.x << " " << copy.y << "\n";
}

vec2 operator+(const vec2& rhs) const {
return vec2(x + rhs.x, y + rhs.y);
}
};

void vec2Add(vec2* dest, const vec2* src1, const vec2* src2) {
dest->x = src1->x + src2->x;
dest->y = src1->y + src2->y;
}

int main()
{
vec2 a(0, 0), b(1, 1), c(2, 2), d(3, 3); //4 constructors called

vec2Add(&a, &a, &b); //a = a + b
vec2Add(&a, &a, &c); //a = a + c // a = a + b + c
vec2Add(&a, &a, &d); //a = a + d // a = a + b + c + d

std::cout << "Using vec2Add, a has values: " << a.x << " " << a.y << "\n\n";

vec2 v1(0, 0), v2(1, 1), v3(2, 2), v4(3, 3); //4 constructors called
v1 = v1 + v2 + v3 + v4;

std::cout << "Using operator+, v1 has values: " << v1.x << " " << v1.y << "\n\n";

std::cin.get();
return 0;
}


This is just a quick example to show the number of times the objects are constructed. Both parts initially create 4 vec2 objects, then perform "a = a + b + c + d" (or, in the second case, "v1 = v1 + v2 + v3 + v4"); both methods have the exact same result. What actually goes on underneath is a bit different, though:

Constructing vector at 002AFD60 with values 0 0
Constructing vector at 002AFD70 with values 1 1
Constructing vector at 002AFD78 with values 2 2
Constructing vector at 002AFD80 with values 3 3
Using vec2Add, a has values: 6 6


Constructing vector at 002AFD68 with values 0 0
Constructing vector at 002AFD88 with values 1 1
Constructing vector at 002AFD90 with values 2 2
Constructing vector at 002AFDA0 with values 3 3
Constructing vector at 002AFD98 with values 1 1
Constructing vector at 002AFDA8 with values 3 3
Constructing vector at 002AFDB0 with values 6 6
Using operator+, v1 has values: 6 6


The second method ended up with 3 additional constructions of vec2 objects. It's not exactly a fair comparison, so I quickly changed it around not to construct v1 until it's assigned a value, which reduced the number of additional constructions to 1. Still, there's at least 1 temporary variable associated with vector addition that is unnecessary.


Beside the fact that the number+type of assembly instructions (and the most optimal order of them being executed) should be the ONLY thing you strive for with non-algorithmic optimization like this (since nothing else makes your program faster), you're completely missing something yet again:

Of course if you print something in the constructor, the compiler won't be able to optimize it away. If you don't have those outputs in the constructor, there will not be any additional unnecessary objects constructed.

If you wanted to make a point that an unoptimized version of the code produces more temporary copies then yeah, you're right, but you're contradicting yourself since you said yourself that this is about opimization, by saying "this is not premature optimization at all"

Please, for the sake of your invested time and anyone who's working with your "optimized code", just don't do it. Take it from someone who has a lot more experience in high-performance optimization in a professional environment than you.
If you value your soul, never look into the eye of a horse. Your soul will forever be lost in the void of the horse.
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2013-01-26 17:40:01
January 26 2013 17:39 GMT
#4649
Let me say this again because I did not stress it enough:

First have a working, well-tested version of your software. Then you can start thinking about which parts should you optimize, if you are unsatisfied with its performance.

Not the other way around.
http://www.fimfiction.net/user/Treasure_Chest
Absurdly
Profile Joined May 2011
Canada59 Posts
January 26 2013 21:40 GMT
#4650
Hello,

Hope you guys don't mind a noobie question. I'm pretty new to programming still and am having a problem with a visual basic program that is supposed to take 5 inputted values in the same textbox(1 value at a time, clearing after each entry) and then display them as they're entered in another multiline texbox below and store them in an array. Next, a loop is to be used on the array to calculate the average of the inputted numbers.

My problem thus far is trying to get the 5 values stored in the array, and both my textbook and google have failed me.

What little I have so far...
+ Show Spoiler +

'Input
inputScore = txtScores.Text
If Not IsNumeric(txtScores.Text) Then
MsgBox("Score must be between 1 and 300")
ElseIf txtScores.Text.Contains(".") Then
MsgBox("Score must be a whole number")
ElseIf txtScores.Text < 1 Or txtScores.Text > 300 Then
MsgBox("Score must be between 1 and 300")
Else : txtAllScores.Text = txtAllScores.Text & vbCrLf & inputScore
End If
' ??? allScores(4) = txtAllScores.Text

Craton
Profile Blog Joined December 2009
United States17281 Posts
Last Edited: 2013-01-27 23:16:47
January 27 2013 00:01 GMT
#4651
Is that your button click event?

Your first error message is wrong, btw. Secondly, if you're going to store your .Text value in a variable, you should use that variable for your error checking instead of going back to the .Text property each time.

Assuming your array is declared with a length of 5, all you need to do is just add the current value to the next slot each time. The simplest method is just to have a class-level integer that you increment each time and use to track which position you're at.

I don't remember offhand if integer arrays have a way to "know" how many values are actually present. The length / count fields just tell you the number of elements (which is 5, since that's how it's declared). You alternatively could just iterate your array with each button click to find which index to use. You could also ReDim each time, but I don't recommend that approach.

List(Of Integer) is much nicer for this kind of thing -- you could simply do a .Add(someval) each time. I'm assuming that this awkwardly forced approach is because of the assignment.

Additionally, you could iterate the multiline listbox during calculate to fill your array and avoid this issue.

I'd do something simple like:
Imports System.Collections.Generic
Public Class Form1
Dim scoreList As List(Of Integer) = New List(Of Integer)

Private Sub btnAddScore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddScore.Click
' <Input Validation Here>
scoreList.Add(Convert.ToInt32(txtOneScore.Text))
txtAllScores.Text += Environment.NewLine & txtOneScore.Text
End Sub

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
For Each i As Int32 In scoreList
' Do something
Next
End Sub
End Class
twitch.tv/cratonz
omarsito
Profile Joined June 2011
22 Posts
January 27 2013 19:47 GMT
#4652
I'm doing a home exercise about C programming and im kinda stuck on the first question about memory allocation and I'd be glad if someone could try to explain this to me.

Code:+ Show Spoiler +
10 #include <malloc.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 int gi; /* Global variable. */
15 int in = 4711; /* Global variable, initialized to 4711. */
16
17 int fun( int parm )
18 {
19 /* Local variable, initialized every time fun is called. */
20 int loc1 = parm + 17;
21
22 printf( "AF.1: loc1 stored at %lx (hex); value is %d (dec), %x (hex)\n",
23 (long) &loc1, loc1, loc1 );
24 printf( "AF.2: parm stored at %lx (hex); value is %d (dec), %x (hex)\n",
25 (long) &parm, parm, parm );
26
27 gi = parm; /* Change the value of a global variable. */
28 printf( "AF.3: Executed gi = parm;\n" );
29 return( loc1 );
30 }
31
32 /* Main function. */
33 int main()
34 {
35 /* Local variables. */
36 int m;
37 int n;
38 int * p; /* Declare p as pointer, so that p can hold an address. */
39 /* Do some calculation. */
40 gi = 12345;
41 m = gi + 11111;
42 n = 17;
43printf( "Message AM.01 from areas.c: Hello, World!\n" );
45
46 printf( "AM.02: m: stored at %lx (hex); value is %d (dec), %x (hex)\n",
47 (long) &m, m, m );
48 printf( "AM.03: n: stored at %lx (hex); value is %d (dec), %x (hex)\n",
49 (long) &n, n, n );
50 printf( "AM.04: gi: stored at %lx (hex); value is %d (dec), %x (hex)\n",
51 (long) &gi, gi, gi );
52 printf( "AM.05: in: stored at %lx (hex); value is %d (dec), %x (hex)\n",
53 (long) &in, in, in );
54
55 printf( "AM.06: fun: address is %lx (hex)\n", (long) fun );
56 printf( "AM.07: main: address is %lx (hex)\n", (long) main );
57
58 p = (int *) malloc( sizeof( int ) );
59 printf( "AM.08: Executed p = (int *) malloc( sizeof( int ) );\n" );
60 printf( "AM.09: p: stored at %lx (hex); value is %ld (dec), %lx (hex)\n",
61 (long) &p, (long) p, (long) p );
62
63 printf( "AM.10: Will soon execute n = fun( m );\n" );
64 n = fun( m );
65 printf( "AM.11: Has now returned from n = fun( m );\n" );
66
67 printf( "AM.12: n: stored at %lx (hex); value is %d (dec), %x (hex)\n",
68 (long) &n, n, n );
69 printf( "AM.13: gi: stored at %lx (hex); value is %d (dec), %x (hex)\n",
70 (long) &gi, gi, gi );
71
72 free( p );
73 exit( 0 );
74 }

Now the exercise wants me to list in what memory area is the variables gi,in,m,p and what memory area does the pointer p point to, and the answer to these questions i can choose between code, data, bss, stack or heap

now what i've figured out is that all variables declared in the main function is put on the stack and the pointer itself is put on the stack. But i cant figure what decides if the variable is either put on data, bss or heap
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2013-01-27 20:03:08
January 27 2013 19:52 GMT
#4653
For future reference, when posting code, please use proper indentation so we can read it more easily.


int main()
{
int foo = 1;
return foo;
} // This is good

int main()
{
int foo = 1;
return foo;
} // This is bad



To answer your question, you simply need to find a decent definition of the different memory segments, and then look at where each variable is being declared and assigned. Here's a good start: http://en.wikipedia.org/wiki/Data_segment


Definitions are roughly,

global/static/etc - data
global/static/etc uninitialized - bss
function local variables - stack
blocks of data controlled by malloc - heap

---

the actual bits that represent instructions in your code (think assembly) - code





An important point in computer security is that without proper care, you can accidentally (or purposefully) write stuff into the wrong section. Buffer overflow is fun
Who after all is today speaking about the destruction of the Armenians?
Ilikestarcraft
Profile Blog Joined November 2004
Korea (South)17733 Posts
Last Edited: 2013-01-27 19:58:10
January 27 2013 19:57 GMT
#4654
Was playing around if the indent tag works in the code brackets and accidently pressed post instead of preview. oops
ils
"Nana is a goddess. Or at very least, Nana is my goddess." - KazeHydra
waxypants
Profile Blog Joined September 2009
United States479 Posts
January 28 2013 02:05 GMT
#4655
bss is for zero-initialized stuff which includes uninitialized global and static variables (which are initialized to 0 by default) or the same types which are explicitly (redundantly) initialized to 0.
Mistakes
Profile Joined February 2011
United States1102 Posts
Last Edited: 2013-01-28 04:04:46
January 28 2013 03:33 GMT
#4656
EDIT: JAVA

Hi all,
I just found this thread not too long ago and am having trouble starting this project. The project is as follows:

+ Show Spoiler +
Write a grading program for a class with the following grading policies:
a. There are three quizzes, each graded on the basis of 10 points.
b. There is one midterm exam, graded on the basis of 100 points.
c. There is one final exam, graded on the basis of 100 points.
The final exam counts for 40% of the grade. The midterm counts for 35% of the
grade. The three quizzes together count for a total of 25% of the grade. (Do not
forget to convert the quiz scores to percentages before they are averaged in.)
Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a
B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but
less than 70) is a D, and any grade below 60 is an F. The program should read in
the student’s scores and output the student’s record, which consists of three quiz
scores and two exam scores, as well as the student’s overall numeric score for the
entire course and final letter grade.
Define and use a class for the student record. The class should have instance variables
for the quizzes, midterm, final, overall numeric score for the course, and
final letter grade. The overall numeric score is a number in the range 0 to 100,
which represents the weighted average of the student’s work. The class should have
methods to compute the overall numeric grade and the final letter grade. These last
methods should be void methods that set the appropriate instance variables. Your
class should have a reasonable set of accessor and mutator methods, an equals
method, and a toString method, whether or not your program uses them. You
may add other methods if you wish.


Additional information:
Use two classes to do this assignment. Name the first class TestGrade, it will be a driver class that is to create an instance of the second class, prompt and get values, and display values. The second class will be named Grade, this is where all the core logic in contained.

I always seem to have trouble getting the ball rolling, but once I do I can generally figure out where to head from there. Any tips on getting this set up would be greatly appreciated! Feel free to PM as well.

Thanks!
StarCraft | www.psistorm.com | www.twitter.com/MistakesSC | www.twitch.tv/MistakesSC | Seattle
DeltaX
Profile Joined August 2011
United States287 Posts
January 28 2013 05:11 GMT
#4657
On January 28 2013 12:33 Mistakes wrote:
EDIT: JAVA

Hi all,
I just found this thread not too long ago and am having trouble starting this project. The project is as follows:

+ Show Spoiler +
Write a grading program for a class with the following grading policies:
a. There are three quizzes, each graded on the basis of 10 points.
b. There is one midterm exam, graded on the basis of 100 points.
c. There is one final exam, graded on the basis of 100 points.
The final exam counts for 40% of the grade. The midterm counts for 35% of the
grade. The three quizzes together count for a total of 25% of the grade. (Do not
forget to convert the quiz scores to percentages before they are averaged in.)
Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a
B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but
less than 70) is a D, and any grade below 60 is an F. The program should read in
the student’s scores and output the student’s record, which consists of three quiz
scores and two exam scores, as well as the student’s overall numeric score for the
entire course and final letter grade.
Define and use a class for the student record. The class should have instance variables
for the quizzes, midterm, final, overall numeric score for the course, and
final letter grade. The overall numeric score is a number in the range 0 to 100,
which represents the weighted average of the student’s work. The class should have
methods to compute the overall numeric grade and the final letter grade. These last
methods should be void methods that set the appropriate instance variables. Your
class should have a reasonable set of accessor and mutator methods, an equals
method, and a toString method, whether or not your program uses them. You
may add other methods if you wish.


Additional information:
Use two classes to do this assignment. Name the first class TestGrade, it will be a driver class that is to create an instance of the second class, prompt and get values, and display values. The second class will be named Grade, this is where all the core logic in contained.

I always seem to have trouble getting the ball rolling, but once I do I can generally figure out where to head from there. Any tips on getting this set up would be greatly appreciated! Feel free to PM as well.

Thanks!


"How do I start" is a bit general. What specifically do you not understand about the project? If you want to know what to do first, I would write the code to get the scores from the user (are the scores in a text file? user input? other? I assume you know this). After that the assignment is pretty clear what you have to do with that information.
HeavenS
Profile Joined August 2004
Colombia2259 Posts
Last Edited: 2013-01-28 05:31:12
January 28 2013 05:30 GMT
#4658
Hey guys this thread seems very very informative. I seem to have gotten late to the party, wow 233 pages! Anyways im kinda having a bit of an issue. You see, i was a civil engineering major, however as of lately ive really lost interest in it. I've found that as i learn more and more about what the daily job of a civil engineer is, it interests me less and less. This kinda sucks because it was really all i had thought about studying, however im pretty much about 90% sure that im going to switch my major now rather than finish it only to be bored of it! Seeing as how i like computers so much, and i love visiting the xda-dev website to read up on topics and it always amazes me how the devs there accomplish things, i've thought that maybe software engineering would be a good major to switch to. I think it might offer me that space to be creative and i could put the skills learned to making my own programs in my spare time and who knows maybe even an app or something.

I've also read that job prospects are very good and you can be employed in a great variety of places. The major i was eyeing is Computer Science, with a software development track (as is stated by my university). Switching to this major would allow me to make use of the math that i've learned thus far and i wouldn't have to start from zero because of the overlapping classes up to a certain point. However, i have never EVER done any programming whatsoever and honestly don't even know where to start. So here's my question to you guys. I have four months of free time until my semester at the uni starts and i want to put it to good use. I want to dip my feet into programming so when i start Uni i wont be completely clueless. I THINK the first programming course at the Uni is Java. That being said, what should i devote these next four months to? I obviously read the op but its still not clear to me which language i should devote to first? Should i start with java since i'll be learning java first course anyways? Or should i do c++? IDK! please give me some advice!
Im cooler than the other side of the pillow.
WindWolf
Profile Blog Joined July 2012
Sweden11767 Posts
January 28 2013 06:13 GMT
#4659
Anyone got any good tips for C# books, as I'm thinking if familiarizing myself with that language later in the spring.
On January 28 2013 14:30 HeavenS wrote:
I have four months of free time until my semester at the uni starts and i want to put it to good use. I want to dip my feet into programming so when i start Uni i wont be completely clueless. I THINK the first programming course at the Uni is Java. That being said, what should i devote these next four months to? I obviously read the op but its still not clear to me which language i should devote to first? Should i start with java since i'll be learning java first course anyways? Or should i do c++? IDK! please give me some advice!

If you are going to learn Java first, then I'd recommend that you familiarize yourself with it. Java is IMO not an overomplecated language for beginner. Plus it has (compared to C++) a big standard library, so that you won't feel that you have to reinvent the wheel several times over.

But if you are going to learn C++ later on (which is the way I interpret it), I have to say that learning about dynamic memory allocation and C++-pointers might be confusing at first.
EZ4ENCE
DertoQq
Profile Joined October 2010
France906 Posts
Last Edited: 2013-01-28 06:44:02
January 28 2013 06:31 GMT
#4660
I think starting with java is a big mistake. It gives people really bad habits and will make you very confused when you start coding in C/C++.

you should read that : http://stackoverflow.com/questions/143820/i-can-learn-either-c-or-java-which-one-should-i-choose-first-should-i-take-the
"i've made some empty promises in my life, but hands down that was the most generous" - Michael Scott
Prev 1 231 232 233 234 235 1032 Next
Please log in or register to reply.
Live Events Refresh
WardiTV Team League
11:00
Group A
WardiTV738
RotterdaM677
IndyStarCraft 332
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 677
IndyStarCraft 332
Hui .268
LamboSC2 198
Railgan 17
StarCraft: Brood War
Britney 48535
Jaedong 3277
BeSt 873
EffOrt 766
Mini 620
ggaemo 492
actioN 449
Shuttle 419
Stork 419
ZerO 385
[ Show more ]
Rush 347
Killer 328
Zeus 292
firebathero 291
Hyuk 259
Soulkey 251
Last 123
hero 96
Larva 89
Light 77
Sea.KH 67
Sharp 66
PianO 64
ToSsGirL 63
sSak 55
sorry 52
Hyun 47
Aegong 38
Bale 37
Shine 36
Movie 35
JYJ 27
Rock 18
Sacsri 17
Terrorterran 15
GoRush 13
IntoTheRainbow 12
Icarus 9
SilentControl 8
eros_byul 1
Dota 2
Gorgc7773
BananaSlamJamma129
Counter-Strike
fl0m1960
edward140
Heroes of the Storm
Khaldor236
Other Games
FrodaN10049
singsing2247
Liquid`RaSZi1294
B2W.Neo1216
Fuzer 214
KnowMe178
crisheroes151
Mew2King49
ZerO(Twitch)15
Organizations
StarCraft 2
ComeBackTV 473
Other Games
gamesdonequick421
BasetradeTV139
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• HeavenSC 25
• Adnapsc2 11
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV809
League of Legends
• Nemesis4139
• Jankos2730
Upcoming Events
BSL
4h 14m
Replay Cast
9h 14m
Replay Cast
18h 14m
Afreeca Starleague
19h 14m
Light vs Calm
Royal vs Mind
Wardi Open
20h 14m
Monday Night Weeklies
1d 1h
OSC
1d 9h
Sparkling Tuna Cup
1d 19h
Afreeca Starleague
1d 19h
Rush vs PianO
Flash vs Speed
Replay Cast
2 days
[ Show More ]
Afreeca Starleague
2 days
BeSt vs Leta
Queen vs Jaedong
Replay Cast
3 days
The PondCast
3 days
Replay Cast
4 days
RSL Revival
4 days
Replay Cast
5 days
RSL Revival
5 days
BSL
6 days
RSL Revival
6 days
uThermal 2v2 Circuit
6 days
Liquipedia Results

Completed

Proleague 2026-03-27
WardiTV Winter 2026
Underdog Cup #3

Ongoing

BSL Season 22
CSL Elite League 2026
CSL Season 20: Qualifier 1
ASL Season 21
Acropolis #4 - TS6
2026 Changsha Offline CUP
StarCraft2 Community Team League 2026 Spring
RSL Revival: Season 4
Nations Cup 2026
NationLESS Cup
BLAST Open Spring 2026
ESL Pro League S23 Finals
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual

Upcoming

CSL Season 20: Qualifier 2
Escore Tournament S2: W1
CSL 2026 SPRING (S20)
Acropolis #4
IPSL Spring 2026
BSL 22 Non-Korean Championship
CSLAN 4
Kung Fu Cup 2026 Grand Finals
HSC XXIX
uThermal 2v2 2026 Main Event
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
IEM Atlanta 2026
Asian Champions League 2026
PGL Astana 2026
BLAST Rivals Spring 2026
CCT Season 3 Global Finals
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.