Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

Speeding up Java I/O - Read method

The following example counts the number of newline bytes ('\n') in a file. It simply uses the read method on a FileInputStream:

 import java.io.*;
  
  public class intro1 {
    public static void main(String args[]) {
      if (args.length != 1) {
        System.err.println("missing filename");
        System.exit(1);
      }
      try {
        FileInputStream fis =
            new FileInputStream(args[0]);
        int cnt = 0;
        int b;
        while ((b = fis.read()) != -1) {
          if (b == '\n')
            cnt++;
        }
        fis.close();
        System.out.println(cnt);
      }
      catch (IOException e) {
        System.err.println(e);
      }
    }
  }


Subject to Sun's Code Sample License

FInd slow actions in a Rails app

# Show a list of actions sorted by time taken. Useful for finding slow actions.
cat log/development.log | awk '/Completed/ { print "[" $3 "] - " $0 }' | sort -nr

StopWatch - Why is my app so slow ???

StopWatch is a small class allowing to manage multiple concurrent stopwatches to measure time elapsed between two calls. Nothing is done while time is rolling (no thread, no loop), it only stores and compares timestamps.

import java.util.Hashtable;

public class StopWatch {
    private static final Hashtable startTime = new Hashtable();
    
    public static void start(String id){
        startTime.put(id,new Long(System.currentTimeMillis()));
    }

    public static long stop(String id){
        return System.currentTimeMillis() - ((Long)startTime.remove(id)).longValue();
    }
}


Example of use :
public main(String[] args) {
    // Start a global stopwatch
    StopWatch.start("GLOBAL");

    // evaluate time used by task 1
    StopWatch.start("TASK1");
    executeTask1();
    System.out.println("Time elapsed for task 1 : " + StopWatch.stop("TASK1") + "ms";

    // evaluate time used by task 2
    StopWatch.start("TASK2");
    executeTask2();
    System.out.println("Time elapsed for task 2 : " + StopWatch.stop("TASK2") + "ms";

    // Display time elapsed for full processing
    System.out.println("Total processing time : " + StopWatch.stop("GLOBAL") + "ms";
}

Switch Oracle CLOB to VARCHAR2

This rake task creates a database script to change all Oracle CLOB columns to VARCHAR2 columns.

Changing Oracle CLOBs to VARCHAR2s can result in a huge performance increase, especially if the database and app servers are not close together on the network.

namespace :db do
  task :fix_clobs => [:environment] do |t|
    @outfile = File.expand_path(File.join(RAILS_ROOT,"db","fix_clobs.sql"))
  
    File.open(@outfile, "w") do |file|
      ActiveRecord::Base.connection.tables.each do |table_name|
        begin
          model = eval(table_name.classify)
          model.columns.each do |column|
            if column.sql_type == "CLOB"
              file.write("ALTER TABLE #{table_name} ADD #{column.name}_temp VARCHAR2(4000);\n")
              file.write("UPDATE #{table_name} SET #{column.name}_temp = #{column.name};\n")
              file.write("COMMIT;\n")
              file.write("ALTER TABLE #{table_name} DROP COLUMN #{column.name};\n")
              file.write("ALTER TABLE #{table_name} RENAME COLUMN #{column.name}_temp TO #{column.name};\n")
              file.write("\n")
            end
          end
         rescue => ex
           puts "Failed for #{table_name} with #{ex.class}"
         end
      end
    end
  end
end

High-performance Ruby: faster Symbol.to_s

Here's something that I found useful for shaving a few microseconds off. The performance gain ranges between 10% and 35%! YMMV.

Note: updated with suggestion by trans.

class Symbol
  def to_s
    @str_rep || (@str_rep = id2name.freeze)
  end
end

Analyse a MySQL Table for Inefficiencies

// description of your code here

SELECT * FROM tags PROCEDURE ANALYSE()

Analyse a MySQL Query for inefficiencies

// description of your code here

EXPLAIN SELECT t2.dbid, t2.tag, COUNT(t2.dbid) * 20 AS match_count
FROM tags AS t1, tags AS t2
WHERE t1.dbid = '105318'
AND t2.tag = t1.tag
AND t1.dbid != t2.dbid
GROUP BY t2.dbid
ORDER BY match_count;

Setup for Performance Testing: Clear cache, buffers (MSSQL)

For Microsoft SQL (MSSQL).
Use this to clear the cache and buffers to ensure comparison are accurate.

dbcc freeproccache
go
dbcc dropcleanbuffers
go
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS