• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 10:15
CEST 16:15
KST 23:15
  • 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
Maestros of the Game: Week 1/Play-in Preview12[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy13
Community News
LiuLi Cup - September 2025 Tournaments2Weekly Cups (August 25-31): Clem's Last Straw?39Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris53Weekly Cups (Aug 11-17): MaxPax triples again!15
StarCraft 2
General
Geoff 'iNcontroL' Robinson has passed away #1: Maru - Greatest Players of All Time Production Quality - Maestros of the Game Vs RSL 2 Heaven's Balance Suggestions (roast me) Maestros of the Game: Week 1/Play-in Preview
Tourneys
RSL: Revival, a new crowdfunded tournament series Sea Duckling Open (Global, Bronze-Diamond) Maestros of The Game—$20k event w/ live finals in Paris LiuLi Cup - September 2025 Tournaments Sparkling Tuna Cup - Weekly Open Tournament
Strategy
Custom Maps
External Content
Mutation # 489 Bannable Offense Mutation # 488 What Goes Around Mutation # 487 Think Fast Mutation # 486 Watch the Skies
Brood War
General
BW General Discussion ASL20 General Discussion Victoria gamers Pros React To: herO's Baffling Game BGH Auto Balance -> http://bghmmr.eu/
Tourneys
[IPSL] ISPL Season 1 Winter Qualis and Info! [Megathread] Daily Proleagues Is there English video for group selection for ASL Small VOD Thread 2.0
Strategy
Simple Questions, Simple Answers Muta micro map competition Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Nintendo Switch Thread Path of Exile Warcraft III: The Frozen Throne
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
Russo-Ukrainian War Thread The Games Industry And ATVI Canadian Politics Mega-thread European Politico-economics QA Mega-thread Things Aren’t Peaceful in Palestine
Fan Clubs
The Happy Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! [\m/] Heavy Metal Thread
Sports
MLB/Baseball 2023 2024 - 2026 Football Thread Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s)
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
Collective Intelligence: Tea…
TrAiDoS
A very expensive lesson on ma…
Garnet
hello world
radishsoup
Lemme tell you a thing o…
JoinTheRain
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
INDEPENDIENTE LA CTM
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1298 users

The Big Programming Thread - Page 233

Forum Index > General Forum
Post a Reply
Prev 1 231 232 233 234 235 1031 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 States17250 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)17727 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
"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 1031 Next
Please log in or register to reply.
Live Events Refresh
Cosmonarchy
14:00
Showmatch #4
TriGGeR vs YoungYakov
YoungYakov vs HonMonO
HonMonO vs TriGGeR
LiquipediaDiscussion
CranKy Ducklings
10:00
Sea Duckling Open #138
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
IndyStarCraft 108
SKillous 84
StarCraft: Brood War
Calm 6953
Jaedong 2678
Larva 935
EffOrt 895
firebathero 737
BeSt 529
ZerO 443
Stork 423
actioN 339
Rush 269
[ Show more ]
Mini 236
ggaemo 230
Nal_rA 158
Hyuk 151
Last 140
PianO 121
TY 95
Yoon 86
Movie 62
Free 59
ToSsGirL 49
Backho 35
Noble 33
sorry 27
zelot 24
yabsab 19
ajuk12(nOOB) 18
sSak 12
HiyA 10
SilentControl 9
Terrorterran 9
Icarus 6
ivOry 4
Dota 2
The International52790
Gorgc15276
Dendi782
qojqva620
Fuzer 277
XcaliburYe113
League of Legends
JimRising 409
Heroes of the Storm
Liquid`Hasu362
Khaldor225
Other Games
singsing1377
B2W.Neo1338
crisheroes389
Hui .264
SortOf240
mouzStarbuck113
ToD88
KnowMe56
QueenE54
ZerO(Twitch)17
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• Pr0nogo 3
• FirePhoenix2
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV170
League of Legends
• Nemesis3260
• Jankos333
Upcoming Events
Maestros of the Game
2h 45m
Solar vs Bunny
Clem vs Rogue
[BSL 2025] Weekly
3h 45m
OSC
7h 45m
RSL Revival
19h 45m
Cure vs Bunny
Creator vs Zoun
Maestros of the Game
1d 2h
Maru vs Lambo
herO vs ShoWTimE
BSL Team Wars
1d 4h
Team Hawk vs Team Sziky
Sparkling Tuna Cup
1d 19h
Monday Night Weeklies
2 days
The PondCast
4 days
Online Event
5 days
[ Show More ]
BSL Team Wars
6 days
Team Bonyth vs Team Dewalt
BSL Team Wars
6 days
Maestros of the Game
6 days
Liquipedia Results

Completed

Proleague 2025-09-02
SEL Season 2 Championship
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
CSL 2025 AUTUMN (S18)
LASL Season 20
RSL Revival: Season 2
Maestros of the Game
Chzzk MurlocKing SC1 vs SC2 Cup #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1

Upcoming

2025 Chongqing Offline CUP
BSL Polish World Championship 2025: Warsaw LAN
BSL Season 21
BSL 21 Team A
EC S1
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
MESA Nomadic Masters Fall
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
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 © 2025 TLnet. All Rights Reserved.