c++ difference from java
1. take charge of object management , negotiate ownershiop ,use scoped_ptr,
not to transfer other's ownership
2. use c++ template to express seperation corncern ,such as (static)polymorphy and policy
3. disable copy constructor and assign operator by yourself
4. polymorphy by pointer
5. 使用 template ,macro 取得類似動態語言的能力
6. 偏好無狀態的 函數
Myisam is preferred without transaction and little
update(delete)
Big than 4G datafile can user Myisam merge table.
InnoDB with auto_increment primary key is preferred.
Few storage process
Guess: 20m
records max per table , 500G
data max per tablespace , 256 tables per database (may problem)
Use prepared statement and batch
Optimize Your Queries For the Query Cache
// query cache does NOT work
$r = mysql_query("SELECT username FROM user WHERE signup_date >= CURDATE()");
// query cache works!
$today = date("Y-m-d");
$r = mysql_query("SELECT username FROM user WHERE signup_date >= '$today'");
EXPLAIN Your SELECT Queries
LIMIT 1 When Getting a Unique Row
Index and Use Same Column Types for Joins
Do Not ORDER BY RAND()
Avoid SELECT *
t is a good habit to always specify which
columns you need when you are doing your SELECT’s.
Use ENUM over VARCHAR
Use NOT NULL If You Can
Store IP Addresses as UNSIGNED INT (?)
Fixed-length (Static) Tables are Faster
Vertical Partitioning
Vertical Partitioning is the act of splitting your table
structure in a vertical manner for optimization reasons.
Example
1: You might have a users table that contains
home addresses, that do not get read often. You can choose to split your table
and store the address info on a separate table. This way your main users table
will shrink in size. As you know, smaller tables perform faster.
Example
2: You have a “last_login” field in your
table. It updates every time a user logs in to the website. But every update on
a table causes the query cache for that table to be flushed. You can put that
field into another table to keep updates to your users table to a minimum.
But you also need to make sure you don’t constantly need to
join these 2 tables after the partitioning or you might actually suffer
performance decline.
Split the Big DELETE or INSERT Queries
If you have some kind of maintenance script
that needs to delete large numbers of rows, just use the LIMIT clause to do it
in smaller batches to avoid this congestion.
Smaller Columns Are Faster
Use an Object Relational Mapper
f you do not need the time component, use
DATE instead of DATETIME.
Consider horizontally spitting many-columned tables if
they contain a lot of NULLs or rarely used columns.
Be an SQL programmer who thinks in sets, not procedural
programming paradigms
InnoDB can’t optimize SELECT COUNT(*) queries. Use counter
tables! That’s how to scale InnoDB.
PreparedStatements are implemented by the driver, as MySQL
does not have a prepared statement feature. Because of this,
the driver does not implement
getParameterMetaData() or
getMetaData() as it would require the
driver to have a complete SQL parser in the client.
Starting with version 3.1.0 MySQL Connector/J, server-side
prepared statements and binary-encoded result sets are used
when the server supports them.
Quick Troubleshooting Tips on Solaris OS and Linux for Java SE 6
This "Quick Start Guide" gives you some quick tips for troubleshooting.
The subsections list some typical functions that can help you in
troubleshooting, including one or more ways to get the
information or perform the action.
Attach the command-line debugger to a core file on a different machine:
On the machine with the core file: jsadebugd path corefile
and on the machine with the debugger: jdb -connect
sun.jvm.hotspot.jdi.SADebugServerAttachingConnector:debugServerName=machine
libumem can be used to debug memory leaks.
Monitoring
Note: The vmID argument for the jstat command is the virtual machine identifier.
See the jstat man page for a detailed explanation.
set nocompatible
set autoindent
set smartindent
set ignorecase
syntax enable
set wrap
set showmatch
set foldmarker={{{,}}}
set tabstop=4
set shiftwidth=4
set ruler
set expandtab
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
set nobackup
setlocal noswapfile
set bufhidden=hide
syntax on
set tags=./tags,~/apsara/tags
set path+=/usr/include/c++/**,~/apsara/include/**
filetype plugin on
filetype indent on
autocmd filetype java,c,cpp setlocal textwidth=100
set pastetoggle=<F7>
Be aware of context
Extreme maintenance
Be pragmatic
Extreme abstract: Program to an interface (abstraction), not an implementation
Extreme separation of concerns
Extreme readability
Testability
No side effect
Do not repeat yourself
三. Principle
DIP ,dependency inversion of control
OCP , open close
LSP , liskov substitute
ISP , interface segregation
SRP , single responsibility
LKP, Lease knowledge principle
四. design pattern
Construction
Behavior
Structure
五. anti-pattern、bad smell
Long method
Diverse change
Repeated code
Talk to stranger
Pre optimize
六. algorithms
nLongN
Divided and conqueror
七. architecture
Hierarchal
Pipes and filter
Micro kernel
Broker
Black Board
Interpreter
八. Distributed & concurrent
What to concurrent
Scalability
Stretch key dimensions to see what breaks
九. languages
Ruby
Erlang
assemble
C
C++
Java
Python
Scala
Be ware of different program paradigms.
十. Performance
Minimize remote calls and other I/O
Speed-up data conversion
release resource as soon as possible
十一. architectures' future
軟件設計思想的發展邏輯,大致是提高抽象程度 ,separation of concern 程度。
fn(design )= fn1(abstraction )+ fn2(separation of concern).
1. first think algorithm before concurrent
2. first solve top problem
3. memory can be problem with huge data processing
4. not to use refletion frequently
5. prefering strategy that can optimize both cpu and memory .
technical
1. thread synchronizing is how to queuing
be sure to use "while(!Thread.currentThread.isInterupted())
2. prefer high level synchronizing facility to low level methodology such as await,notify
二. operator
三. application
office
erp
mall
game
四. feature
search engine
monitor system
security
dynamic language
special db system
special file system
五. platform
virtual computing resource system
cloud file system
cloud db system
cloud os
六. chance
big fish or small fish should find their way to survive.
Conducting and Reviewing the Software Design Model
The design model resides at the core of the software engineering process. It is the place where quality is built into the software (and the place where quality is assessed. For this checklist, the more questions that elicit a negative response, the higher the risk that the analysis model will adequately serve its purpose. . For this checklist, the more questions that elicit a negative response, the higher the risk that the design model will not adequately serve its purpose.
General issues:
o Does the overall design implement all explicit requirements? Has a traceability table been developed?
設計對需求的匹配?
o Does the overall design achieve all implicit requirements?
o Is the design represented in a form that is easily understood by outsiders?
易理解?
o Is design notation standardized? Consistent?
o Does the overall design provide sufficient information for test case design?
可測試。
o Is the design created using recognizable architectural and procedural patterns?
常用的架構 和模式?
o Does the design strive to incorporate reusable components?
重用組件?
o Is the design modular?
模塊化
o Has the design defined both procedural and data abstractions that can be reused?
重用的過程 / 數據 抽象?
o Has the design been defined and represented in a stepwise fashion?
逐漸細化的表述?
o Has the resultant software architecture been partitioned for ease of implementation? Maintenance?
可部署性? 可維護性?
o Have the concepts of information hiding and functional independence been followed throughout the design?
封裝性?
o Has a Design Specification been developed for the software?
文檔?
For data design:
o Have data objected defined in the analysis model been properly translated into required data structured?
數據映射with analysis?
o Do the data structures contain all attributes defined in the analysis model?
數據屬性?
o Have any new data structures and/or attributes been defined at design time?
新的數據結構?
o How do any new data structures and/or attributes related to the analysis model and to overall user requirements?
用戶需求與數據結構匹配嗎?
o Have the simplest data structures required to do the job been chosen?
數據結構簡單嗎?
o Can the data structures be implemented directly in the programming language of choice?
編程語言適合數據結構?
o How are data communicated between software components?
軟件組件之間的數據交換?
o Do explicit data components (e.g., a database) exist? If so, what is their role?
數據庫?
For architectural design:
o Has a library of architectural styles been considered prior to the definition of the resultant software architecture?
架構模式?
o Has architectural tradeoff analysis been performed?
架構分析的tradeoff?
o Is the resultant software architecture a recognizable architectural style?
認可的架構風格?
o Has the architecture been exercised against existing usage scenarios?
架構有應用示例嗎?
o Has an appropriate mapping been used to translate the analysis model into the architectural model?
分析和架構之間的mapping?
o Can quality characteristics associated with the resultant architecture (e.g., a factored call-and-return architecture) be readily identified from information provided in the design model?
架構的質量特點?
For user interface design:
o Have the results of task analysis been documented?
o Have goals for each user task been identified?
o Has an action sequence been defined for each user task?
o Have various states of the interface been documented?
o Have objects and actions that appear within the context of the interface been defined?
o Have the three "golden rules" (SEPA, 5/e, p. 402) been maintained throughout the GUI design?
o Has flexible interaction been defined as a design criterion throughout the interface?
o Have expert and novice modes of interaction been defined?
o Have technical internals been hidden from the causal user?
o Is the on-screen metaphor (if any) consistent with the overall applications?
o Are icons clear and understandable?
o Is interaction intuitive?
o Is system response time consistent across all tasks?
o Has an integrated help facility been implemented?
o Are all error message displayed by the interface easy to understand? Do they help the user resolve the problem quickly?
o Is color being used effectively?
o Has a prototype for the interface been developed?
o Have user's impressions of the prototype been collected in an organized manner?
For component-level design:
* Have proof of correctness techniques (SEPA, 5/e, Chapter 26) been applied to all algorithms?
算法正確性?
* Has each algorithm been "desk-tested" to uncover errors? Is each algorithm correct?
算法?
* Is the design of the algorithm consistent with the data structured that the component manipulates?
算法?
* Have algorithmic design alternatives been considered? If yes, why was this design chosen?
替代算法考慮了嗎?
* Has the complexity of each algorithm been computed?
每個算法的復雜性考慮了嗎?
* Have structured programming constructs been used throughout?
例子:
import java.util.Vector;
public class SYN {
public synchronized void method (Object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementAt(i)); // violation
}
}
private Vector vector = new Vector (5, 5);
}
更正:
不要在循環體中調用同步方法,如果必須同步的話,推薦以下方式:
import java.util.Vector;
public class SYN {
public void method (Object o) {
}
private void test () {
synchronized{//在一個同步塊中執行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementAt(i));
}
}
}
private Vector vector = new Vector (5, 5);
}
例子:
import java.io.FileInputStream;
public class TRY {
void method (FileInputStream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (Exception e) {}
}
}
private int _sum;
}
更正:
將try/catch塊移出循環
void method (FileInputStream fis) {
try {
for (int i = 0; i < size; i++) {
_sum += fis.read();
}
} catch (Exception e) {}
}
參考資料:
Peter Haggar: "Practical Java - Programming Language Guide".
Addison Wesley, 2000, pp.81 – 83
十九、不要在循環體中實例化變量
在循環體中實例化臨時變量將會增加內存消耗
例子:
import java.util.Vector;
public class LOOP {
void method (Vector v) {
for (int i=0;i < v.size();i++) {
Object o = new Object();
o = v.elementAt(i);
}
}
}
更正:
在循環體外定義變量,并反復使用
import java.util.Vector;
public class LOOP {
void method (Vector v) {
Object o;
for (int i=0;i<v.size();i++) {
o = v.elementAt(i);
}
}
}
一直困擾于 indexSearcher 的重新 new ,query filter 的cache 沒了。
重讀solr ,發現非常好。也許我應該考慮用 solr 了。
Caching
Configurable Query Result, Filter, and Document cache instances
Pluggable Cache implementations
Cache warming in background
When a new searcher is opened, configurable searches are run against it
in order to warm it up to avoid slow first hits. During warming, the
current searcher handles live requests.
Autowarming in background
The
most recently accessed items in the caches of the current searcher are
re-populated in the new searcher, enabing high cache hit rates across
index/searcher changes.
SELECT Name FROM Projects p
WHERE NOT EXISTS(
SELECT * FROM Projects
WHERE Parent=p.VertexId)
2。multilevel operation ,用數據庫的輔助表, 用triger 。
CREATE TABLE ProjectPaths(
VertexId INTEGER,
Depth INTEGER,
Path VARCHAR(300) 。
)
3. 用 hibernate 時,如果 stack over flow,考慮用 stack 代替recursive algrithm
publicvoidtraverseDepthFirst(ASTast) { // Root AST node cannot be null or // traversal of its subtree is impossible. if(ast==null) { thrownewIllegalArgumentException( "node to traverse cannot be null!"); } // Map to hold parents of each // AST node. Unfortunately the AST // interface does not provide a method // for finding the parent of a node, so // we use the Map to save them.
MapparentNodes=newHashMap();
// Start tree traversal with first child // of the specified root AST node.
ASTcurrentNode=ast.getFirstChild();
// Remember parent of first child.
parentNodes.put(currentNode , ast);
// Iterate through nodes, simulating // recursive tree traversal, and add them // to queue in proper order for later // linear traversal. This "flattens" the // into a linear list of nodes which can // be visited non-recursively.
while(currentNode!=null) { // Visit the current node.
strategy.visit(currentNode);
// Move down to current node's first child // if it exists.
ASTchildNode=currentNode.getFirstChild();
// If the child is not null, make it // the current node.
if(childNode!=null) { // Remember parent of the child.
parentNodes.put(childNode , currentNode);
// Make child the current node.
currentNode=childNode;
continue; }
while(currentNode!=null) { // Move to next sibling if any.
ASTsiblingNode=currentNode.getNextSibling();
if(siblingNode!=null) { // Get current node's parent. // This is also the parent of the // sibling node.
ASTparentNode=(AST)parentNodes.get(currentNode);
// Remember parent of sibling.
parentNodes.put(siblingNode , parentNode);
// Make sibling the current node.
currentNode=siblingNode;
break; } // Move up to parent if no sibling. // If parent is root node, we're done.
/**
* Returns the node's children.
*
* @return List
*
* @hibernate.list cascade="all-delete-orphan" inverse="true"
* @hibernate.collection-one-to-many class="net.thogau.website.model.Node"
* @hibernate.collection-index column="position"
* @hibernate.collection-key column="parent_id"
* @struts.form-field
*/
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
}
/**
* Returns the position of the node in the children list (if it has parent).
* @return int
*
* @hibernate.property column="position"
*/
public int getPosition() {
try{
return parent.getChildren().indexOf(this);
}
catch(NullPointerException e){
// if it has no parent, position makes no sense
return -1;
}
}
public void setPosition(int position) { /* not used */ }
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(1036586079, -537109207).append(this.name)
.append(this.parent.getName()).append(this.id)
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("name", this.name).append("parent", this.parent)
.append("id", this.id).append("position", this.getPosition()).toString();
}
}
好像,equal ,hash 是必須的。
# /**
# * 樹形遍歷
# * 不用遞歸,用堆棧.
# * 這里只是做為例子,本人不建議把業務邏輯封裝在Entity層.
# */
# public List getVisitResults() {
# List l = new ArrayList();
# Stack s = new Stack();
# s.push(this);
# while (s.empty() == false) {
# Cat c = (Cat) s.pop();
# l.add(c);
# List children = c.getChildren();
# if (children != null) {
# for (int i = 0; i < hildren.size(); i++) {
# Cat cat = (Cat) children.get(i);
# s.push(cat);
# }//end for
# }//end if
# }//end while
# return l;
# }
public void testMediator(){ Mediator m = new Mediator(); DataProviderColleague c1 = new DataProviderColleague(m); DataConsumerColleague c2 = new DataConsumerColleague(); m.IntroduceColleagues(c1,c2);
Over a decade into XML evolution, however, these parsing technologies are slowly showing their age, requiring bypasses and optimizations to overcome their well-known limitations. StAX, or Streaming API for XML, is the new-age XML parser that offers the best features of the existing models, and at the same time provides high performance and efficient access to the underlyi 閱讀全文